在参数中,避免意外地更改参数值并引入一个微妙的错误是非常有用的。我过去常常忽略这个建议,但是在花了4个小时之后。在一个糟糕的方法中(有数百行代码和多个 fors、嵌套的 if 和各种各样的错误做法) ,我建议你这样做。
public int processSomethingCritical( final int x, final int y ){
// hundreds of lines here
// for loop here...
int x2 = 0;
x++; // bug aarrgg...
// hundreds of lines there
// if( x == 0 ) { ...
}
public static class CircleToolsBetter {
public final static double PI = 3.141;
public double getCircleArea(final double radius) {
return (Math.pow(radius, 2) * PI);
}
}
public static String someMethod(final String environmentKey) {
final String key = "env." + environmentKey;
System.out.println("Key is: " + key);
return (System.getProperty(key));
}
}
在此类中,您将构建一个有作用域的 final 变量,该变量将前缀添加到参数環 Key 中。在这种情况下,final 变量仅在执行范围内为 final,这在方法的每次执行中是不同的。每次输入方法时,都会重新构造 final。一旦构造完成,就不能在方法执行的范围内对其进行更改。这允许您在方法的持续时间内修复方法中的变量。见下文:
public class FinalVariables {
public final static void main(final String[] args) {
System.out.println("Note how the key variable is changed.");
someMethod("JAVA_HOME");
someMethod("ANT_HOME");
}
}
最终常数
public double equation2Better(final double inputValue) {
final double K = 1.414;
final double X = 45.0;
double result = (((Math.pow(inputValue, 3.0d) * K) + X) * M);
double powInputValue = 0;
if (result > 360) {
powInputValue = X * Math.sin(result);
} else {
inputValue = K * Math.sin(result); // <= Compiler error
}
final String name;
switch(pluginType) {
case CANDIDATE_EXPORT:
name = "Candidate Stuff";
break;
case JOB_POSTING_IMPORT:
name = "Blah";
break;
default:
throw new IllegalStateException();
}
String name;
switch(pluginType) {
case CANDIDATE_EXPORT:
name = "Candidate Stuff";
//break; whoops forgot break..
//this will cause a compile error for final ;P @Recurse
case JOB_POSTING_IMPORT:
name = "Blah";
break;
}
// code, code, code
// Below is not possible with final
name = "Whoops bug";
由于错误设置的名称(除了忘记了 break,这也是另一个错误) ,我现在可以意外地这样做:
String name;
switch(pluginType) {
case CANDIDATE_EXPORT:
name = "Candidate Stuff";
break;
//should have handled all the cases for pluginType
}
// code, code, code
// Below is not possible with final
name = "Whoops bug";
type plugin = CandidateExport | JobPostingImport
let p = CandidateExport
let name = match p with
| CandidateExport -> "Candidate Stuff"
| JobPostingImport -> "Blah" ;;
match ... with ...的计算结果类似于一个函数 ie 表达式。注意它看起来像我们的 switch 语句。
下面是 Scheme (Racket 或 Chicken)中的一个例子:
(define name
(match b
['CandidateExport "Candidate Stuff"]
['JobPostingImport "Blah"]))