在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
当前回答
有效的Java有一个条目写着“偏爱不可变对象”。将字段声明为final可以帮助您在这方面迈出一小步,但是对于真正的不可变对象来说,当然还有更多的事情要做。
如果您知道对象是不可变的,那么可以在多个线程/客户端之间共享它们以供读取,而无需担心同步问题,并且更容易推断程序的运行方式。
其他回答
选择为每个方法中的每个参数输入final会让编码员和代码读者感到非常恼火。
一旦愤怒超出合理范围,切换到Scala,默认情况下参数是最终的。
或者,您总是可以使用代码样式工具,它将自动为您完成这些工作。所有ide都实现了它们或作为插件。
我很少在方法或类上使用final,因为我喜欢允许人们重写它们。
否则,我只使用finally如果它是一个公共/私有静态最终类型SOME_CONSTANT;
我将它用于方法内部和外部的常量。
我有时只将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于什么原因)。
至于类,我只对一些基础类使用了final类。
IntelliJ IDEA会在函数参数被写入函数内部时发出警告。我已经停止使用final作为函数参数了。我在java运行库中也没有看到它们。
听起来,反对使用最后一个关键字的最大论点之一是“这是不必要的”,而且它“浪费空间”。
如果我们承认“final”的许多好处,同时承认它需要更多的输入和空间,我认为Java应该默认将变量设置为“final”,并且如果编码器想要的话,就要求将变量标记为“mutable”。
为:
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.