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

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

你对此有何看法?


当前回答

在使用final关键字之前,您确实需要了解它的全部用途。它可以应用于变量、字段、方法和类,并对它们产生不同的影响

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

关于最后的关键字

其他回答

我从来没有遇到过在变量上有最后一个关键字就能阻止我犯错误的情况,所以目前我认为这是一种巨大的浪费时间。

除非有真正的理由这样做(比如你想要明确指出变量是final的),否则我宁愿不这样做,因为我发现这样做会使代码的可读性降低。

但是,如果您没有发现它会使代码更难阅读或更长时间地编写,那么无论如何都可以使用它。

编辑:作为一个澄清(并试图赢回反对票),我不是说不要将常量标记为最终值,我是说不要做这样的事情:

public String doSomething() {
  final String first = someReallyComplicatedExpressionToGetTheString();
  final String second = anotherReallyComplicatedExpressionToGetAnother();

  return first+second;
}

在我看来,这只是让代码更难阅读。

同样值得记住的是,所有final的作用都是防止你重新分配变量,它并没有使它成为不可变或类似的东西。

在使用final关键字之前,您确实需要了解它的全部用途。它可以应用于变量、字段、方法和类,并对它们产生不同的影响

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

关于最后的关键字

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

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

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

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

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

强烈推荐。

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

为:

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.