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

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

你对此有何看法?


当前回答

Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug. A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better. Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.

其他回答

将类标记为final还可以使一些方法绑定发生在编译时而不是运行时。 考虑下面的“v2.foo()”——编译器知道B不能有子类,所以foo()不能被重写,所以要调用的实现在编译时是已知的。如果类B没有被标记为final,那么v2的实际类型可能是某个扩展B并重写foo()的类。

class A {
    void foo() {
        //do something
    }
}
final class B extends A {
    void foo() {
    }
}
class Test {
    public void t(A v1, B v2) {
        v1.foo();
        v2.foo();
    }
}

Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug. A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better. Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.

我将它用于方法内部和外部的常量。

我有时只将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于什么原因)。

至于类,我只对一些基础类使用了final类。

IntelliJ IDEA会在函数参数被写入函数内部时发出警告。我已经停止使用final作为函数参数了。我在java运行库中也没有看到它们。

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

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

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

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

当在Java中与变量一起使用时,Final提供了c++中常量的替代品。所以当final和static被用于一个变量时,它就变成了不可变的。同时让迁移的c++程序员非常开心;-)

当与引用变量一起使用时,它不允许您重新引用对象,尽管对象可以被操作。

当final与方法一起使用时,它不允许子类重写该方法。

一旦用法非常清楚,就应该谨慎使用。这主要取决于设计,因为在方法上使用final不利于多态性。

只有当你非常确定变量的值不会/不应该被改变时,才应该将它用于变量。还要确保您遵循SUN鼓励的编码约定。int COLOR_RED = 1;(大写字母以下划线分隔)

对于引用变量,只在需要对特定对象的不可变引用时使用它。

关于可读性部分,在使用最终修饰语时,注释起着非常重要的作用。