在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
当前回答
对于争论,我认为不需要。大多数情况下,它们只会损害可读性。重新分配一个参数变量是如此疯狂的愚蠢,我应该相当有信心,他们可以被视为常量。
Eclipse将最终结果显示为红色,这使得在代码中更容易发现变量声明,我认为这在大多数情况下提高了可读性。
我试图强制执行规则,任何和所有变量都应该是最终的,没有一个非常有效的理由不这样做。如果你只需要找到初始化并确信这就是初始化,那么回答“这个变量是什么?”的问题就容易得多了。
实际上,我现在对非最终变量相当紧张。这就像把刀挂在你的头上,还是把它放在厨房抽屉里的区别……
final变量是标记值的好方法。
一个非最终变量被绑定到一些容易出错的算法的一部分。
一个很好的特性是,当一个算法无法选择使用变量时,大多数情况下解决方案是编写一个方法,这通常会显著改善代码。
其他回答
听起来,反对使用最后一个关键字的最大论点之一是“这是不必要的”,而且它“浪费空间”。
如果我们承认“final”的许多好处,同时承认它需要更多的输入和空间,我认为Java应该默认将变量设置为“final”,并且如果编码器想要的话,就要求将变量标记为“mutable”。
我将它用于方法内部和外部的常量。
我有时只将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于什么原因)。
至于类,我只对一些基础类使用了final类。
IntelliJ IDEA会在函数参数被写入函数内部时发出警告。我已经停止使用final作为函数参数了。我在java运行库中也没有看到它们。
将类标记为final还可以使一些方法绑定发生在编译时而不是运行时。 考虑下面的“v2.foo()”——编译器知道B不能有子类,所以foo()不能被重写,所以要调用的实现在编译时是已知的。如果类B没有被标记为final,那么v2的实际类型可能是某个扩展B并重写foo()的类。
class A {
void foo() {
//do something
}
}
final class B extends A {
void foo() {
}
}
class Test {
public void t(A v1, B v2) {
v1.foo();
v2.foo();
}
}
为:
Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.) Final static fields - Although I use enums now for many of the cases where I used to use static final fields.
考虑但审慎地使用:
最终类——框架/API设计是我唯一考虑的情况。 Final方法——基本上与Final类相同。如果你疯狂地使用模板方法模式,并把东西标记为final,你可能太依赖继承而不是委托。
忽略,除非感觉肛门:
Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.
为事件监听器使用匿名本地类等是Java中的常见模式。 final关键字最常见的用法是确保偶数侦听器可以访问作用域内的变量。
但是,如果您发现自己被要求在代码中放入大量的最终语句。这可能是你做错事的好暗示。
上面的文章给出了这样一个例子:
public void doSomething(int i, int j) {
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};
}