在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.

其他回答

对于将所有可能的变量都声明为final,我非常武断。这包括方法参数、局部变量,以及很少的值对象字段。我有三个在任何地方声明最终变量的主要原因:

Declaring Intention: By declaring a final variable, I am stating that this variable is meant to be written to only once. It's a subtle hint to other developers, and a big hint to the compiler. Enforcing Single-use Variables: I believe in the idea that each variable should have only one purpose in life. By giving each variable only one purpose, you reduce the time it takes to grok the purpose of that particular variable while debugging. Allows for Optimization: I know that the compiler used to have performance enhancement tricks which relied specifically on the immutability of a variable reference. I like to think some of these old performance tricks (or new ones) will be used by the compiler.

然而,我确实认为final类和方法远不如final变量引用有用。最后一个关键字,当与这些声明一起使用时,只是为自动化测试和以您从未预料到的方式使用代码提供了障碍。

我从不在局部变量上使用它们,没有什么意义。即使您不认为变量应该被重新赋值,这对于下一个改变代码的人来说也没有什么区别,而且由于代码正在被更改,任何使其最终的原始目的都可能不再有效。如果只是为了清晰,我认为它失败了,因为冗长的负面影响。

对于成员变量也是如此,因为它们提供的好处很少,除了常量的情况。

它也与不可变无关,因为不可变的最好指标是它被这样记录并且/或没有可以改变对象的方法(这与使类为final是保证它是不可变的唯一方法)。

但是,嘿,这只是我的观点:-)

我认为这一切都与良好的编码风格有关。当然,你可以编写出好的、健壮的程序,而不需要在任何地方使用大量的最终修饰符,但当你考虑到……

将final添加到所有不应该更改的内容中,只会减少您(或下一个编写代码的程序员)误解或误用导致代码生成的思维过程的可能性。至少当他们现在想要改变你以前不变的东西时,它应该敲响一些警钟。

一开始,在你的代码中看到很多最终的关键字看起来有点尴尬,但很快你就会不再注意这个词本身,只会简单地想,从现在开始,这个东西永远不会改变(你可以从我这里得到;-)

我认为这是很好的练习。我并不是一直都在用它,但当我可以并且有意义的时候,我就会这样做。

另一个注意事项是,许多人将final混淆为实例变量的内容不能更改,而不是引用不能更改。

我设置Eclipse在所有未修改的字段和属性上添加final。使用Eclipse“save actions”在保存文件时添加这些最终修饰符(以及其他东西),效果非常好。

强烈推荐。

请查看我关于Eclipse Save Actions的博客文章。