在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
在Java中,有一种惯例,将每个变量(局部变量或类)声明为final参数(如果它们确实是final的话)。
虽然这会使代码更加冗长,但这有助于容易阅读/掌握代码,也可以防止错误,因为意图被清晰地标记出来。
你对此有何看法?
当前回答
我将它用于方法内部和外部的常量。
我有时只将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于什么原因)。
至于类,我只对一些基础类使用了final类。
IntelliJ IDEA会在函数参数被写入函数内部时发出警告。我已经停止使用final作为函数参数了。我在java运行库中也没有看到它们。
其他回答
选择为每个方法中的每个参数输入final会让编码员和代码读者感到非常恼火。
一旦愤怒超出合理范围,切换到Scala,默认情况下参数是最终的。
或者,您总是可以使用代码样式工具,它将自动为您完成这些工作。所有ide都实现了它们或作为插件。
为:
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.
我已经编写了一段时间的代码,并尽可能使用final。这样做了一段时间后(对于变量、方法参数和类属性),我可以说90%(或更多)的变量实际上是最终的。我认为在你不想修改变量的时候不修改变量的好处(我以前看到过,有时这很痛苦)是为了在你的代码中额外的输入和额外的“final”关键字。
也就是说,如果我要设计一种语言,我将使每个变量都是final,除非被其他一些关键字修改。
对于类和方法,我不太使用final。这是一个或多或少复杂的设计选择,除非您的类是一个实用程序类(在这种情况下,您应该只有一个私有构造函数)。
我也使用Collections.unmodifiable…在我需要的时候创建不可修改的列表
我设置Eclipse在所有未修改的字段和属性上添加final。使用Eclipse“save actions”在保存文件时添加这些最终修饰符(以及其他东西),效果非常好。
强烈推荐。
请查看我关于Eclipse Save Actions的博客文章。
在使用final关键字之前,您确实需要了解它的全部用途。它可以应用于变量、字段、方法和类,并对它们产生不同的影响
我建议你看看下面链接的文章,了解更多细节。
关于最后的关键字