在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
当前回答
为:
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可以帮助您在这方面迈出一小步,但是对于真正的不可变对象来说,当然还有更多的事情要做。
如果您知道对象是不可变的,那么可以在多个线程/客户端之间共享它们以供读取,而无需担心同步问题,并且更容易推断程序的运行方式。
另一个注意事项是,许多人将final混淆为实例变量的内容不能更改,而不是引用不能更改。
我将它用于方法内部和外部的常量。
我有时只将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于什么原因)。
至于类,我只对一些基础类使用了final类。
IntelliJ IDEA会在函数参数被写入函数内部时发出警告。我已经停止使用final作为函数参数了。我在java运行库中也没有看到它们。
强烈鼓励使用final作为常量。但是,我不会将它用于方法或类(或者至少考虑一下),因为它使测试更加困难,如果不是不可能的话。如果一定要让一个类或方法成为final,请确保这个类实现了一些接口,这样就可以让一个模拟实现相同的接口。
将类标记为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();
}
}