在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
当前回答
我很少在方法或类上使用final,因为我喜欢允许人们重写它们。
否则,我只使用finally如果它是一个公共/私有静态最终类型SOME_CONSTANT;
其他回答
我认为这一切都与良好的编码风格有关。当然,你可以编写出好的、健壮的程序,而不需要在任何地方使用大量的最终修饰符,但当你考虑到……
将final添加到所有不应该更改的内容中,只会减少您(或下一个编写代码的程序员)误解或误用导致代码生成的思维过程的可能性。至少当他们现在想要改变你以前不变的东西时,它应该敲响一些警钟。
一开始,在你的代码中看到很多最终的关键字看起来有点尴尬,但很快你就会不再注意这个词本身,只会简单地想,从现在开始,这个东西永远不会改变(你可以从我这里得到;-)
我认为这是很好的练习。我并不是一直都在用它,但当我可以并且有意义的时候,我就会这样做。
为事件监听器使用匿名本地类等是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
}
};
}
我从不在局部变量上使用它们,没有什么意义。即使您不认为变量应该被重新赋值,这对于下一个改变代码的人来说也没有什么区别,而且由于代码正在被更改,任何使其最终的原始目的都可能不再有效。如果只是为了清晰,我认为它失败了,因为冗长的负面影响。
对于成员变量也是如此,因为它们提供的好处很少,除了常量的情况。
它也与不可变无关,因为不可变的最好指标是它被这样记录并且/或没有可以改变对象的方法(这与使类为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变量引用有用。最后一个关键字,当与这些声明一起使用时,只是为自动化测试和以您从未预料到的方式使用代码提供了障碍。
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.