在Java中,有一种惯例,将每个变量(局部变量或类)声明为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.

其他回答

强烈鼓励使用final作为常量。但是,我不会将它用于方法或类(或者至少考虑一下),因为它使测试更加困难,如果不是不可能的话。如果一定要让一个类或方法成为final,请确保这个类实现了一些接口,这样就可以让一个模拟实现相同的接口。

最后一个修饰符,特别是对于变量,是一种让编译器强制执行通常合理的约定的方法:确保一个(局部或实例)变量只被赋值一次(不多不少)。通过确保变量在使用之前被明确赋值,你可以避免常见的NullPointerException:

final FileInputStream in;
if(test)
  in = new FileInputStream("foo.txt");
else
  System.out.println("test failed");
in.read(); // Compiler error because variable 'in' might be unassigned

通过防止变量被多次赋值,可以防止过宽的作用域。而不是这样:

 String msg = null;
 for(int i = 0; i < 10; i++) {
     msg = "We are at position " + i;
     System.out.println(msg);
 }
 msg = null;

我们鼓励你这样做:

 for(int i = 0; i < 10; i++) {
     final String msg = "We are at position " + i;
     System.out.println(msg);
 }

一些链接:

最后的故事(《Hardcore Java》一书的免费章节) 一些最终的模式 明确的任务

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.

我一直用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关键字之前,您确实需要了解它的全部用途。它可以应用于变量、字段、方法和类,并对它们产生不同的影响

我建议你看看下面链接的文章,了解更多细节。

关于最后的关键字