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

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

你对此有何看法?


当前回答

Final应该总是用于常量。当定义变量的规则很复杂时,它甚至对于短期存在的变量(在单个方法中)也很有用。

例如:

final int foo;
if (a)
    foo = 1;
else if (b)
    foo = 2;
else if (c)
    foo = 3;
if (d)        // Compile error:  forgot the 'else'
    foo = 4;
else
    foo = -1;

其他回答

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

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

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

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

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.

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

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

我一直用final来表示对象属性。

final关键字在对象属性上使用时具有可见性语义。基本上,设置最终对象属性的值发生在构造函数返回之前。这意味着只要不让This引用脱离构造函数,并且对所有属性使用final,对象(在Java 5语义下)就可以保证正确构造,而且由于它也是不可变的,所以可以安全地发布到其他线程。

不可变对象不仅仅是关于线程安全。它们还使您更容易推断程序中的状态转换,因为可以更改的空间是故意的,如果始终使用,则完全限制在应该更改的内容上。

I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't need to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes.

我想我应该把大部分课程都定为期末考试,但我还没有养成这个习惯。

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