在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。

虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。

你对此有何看法?


当前回答

对于将所有可能的变量都声明为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变量引用有用。最后一个关键字,当与这些声明一起使用时,只是为自动化测试和以您从未预料到的方式使用代码提供了障碍。

其他回答

有效的Java有一个条目写着“偏爱不可变对象”。将字段声明为final可以帮助您在这方面迈出一小步,但是对于真正的不可变对象来说,当然还有更多的事情要做。

如果您知道对象是不可变的,那么可以在多个线程/客户端之间共享它们以供读取,而无需担心同步问题,并且更容易推断程序的运行方式。

我很少在方法或类上使用final,因为我喜欢允许人们重写它们。

否则,我只使用finally如果它是一个公共/私有静态最终类型SOME_CONSTANT;

我已经编写了一段时间的代码,并尽可能使用final。这样做了一段时间后(对于变量、方法参数和类属性),我可以说90%(或更多)的变量实际上是最终的。我认为在你不想修改变量的时候不修改变量的好处(我以前看到过,有时这很痛苦)是为了在你的代码中额外的输入和额外的“final”关键字。

也就是说,如果我要设计一种语言,我将使每个变量都是final,除非被其他一些关键字修改。

对于类和方法,我不太使用final。这是一个或多或少复杂的设计选择,除非您的类是一个实用程序类(在这种情况下,您应该只有一个私有构造函数)。

我也使用Collections.unmodifiable…在我需要的时候创建不可修改的列表

Final显然应该用在常量上,并加强不可变性,但在方法上还有另一个重要的用途。

Effective Java在这方面有一个完整的项目(项目15),指出了意外继承的陷阱。实际上,如果您没有为继承而设计和记录您的类,那么从它继承可能会带来意想不到的问题(该项目提供了一个很好的例子)。因此,建议在不打算继承的任何类和/或方法上使用final。

That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the final if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful.

I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated.