在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是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.

其他回答

我很少在方法或类上使用final,因为我喜欢允许人们重写它们。

否则,我只使用finally如果它是一个公共/私有静态最终类型SOME_CONSTANT;

对于争论,我认为不需要。大多数情况下,它们只会损害可读性。重新分配一个参数变量是如此疯狂的愚蠢,我应该相当有信心,他们可以被视为常量。

Eclipse将最终结果显示为红色,这使得在代码中更容易发现变量声明,我认为这在大多数情况下提高了可读性。

我试图强制执行规则,任何和所有变量都应该是最终的,没有一个非常有效的理由不这样做。如果你只需要找到初始化并确信这就是初始化,那么回答“这个变量是什么?”的问题就容易得多了。

实际上,我现在对非最终变量相当紧张。这就像把刀挂在你的头上,还是把它放在厨房抽屉里的区别……

final变量是标记值的好方法。

一个非最终变量被绑定到一些容易出错的算法的一部分。

一个很好的特性是,当一个算法无法选择使用变量时,大多数情况下解决方案是编写一个方法,这通常会显著改善代码。

听起来,反对使用最后一个关键字的最大论点之一是“这是不必要的”,而且它“浪费空间”。

如果我们承认“final”的许多好处,同时承认它需要更多的输入和空间,我认为Java应该默认将变量设置为“final”,并且如果编码器想要的话,就要求将变量标记为“mutable”。

将类标记为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();
    }
}

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.