为什么要将局部变量和方法参数标记为“最终”? 在Java中?
在Java中,您可以使用final关键字限定局部变量和方法参数。
public static void foo(final int x) {
final String qwerty = "bar";
}
这样做会导致无法在方法主体中重新分配 x 和 qwerty。
这种做法将您的代码推向不变性的方向,这通常被认为是一个优点。 但是,它也往往会使代码变得混乱,“final”到处出现。 您对Java中局部变量和方法参数的final关键字有何看法?
In Java, you can qualify local variables and method parameters with the final keyword.
public static void foo(final int x) {
final String qwerty = "bar";
}
Doing so results in not being able to reassign x and qwerty in the body of the method.
This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
只要合适,您就应该尝试这样做。 除了在您“意外”尝试修改值时向您发出警告之外,它还向编译器提供可以更好地优化类文件的信息。 这是小罗伯特·西蒙斯 (Robert Simmons, Jr.) 所著的《Hardcore Java》一书中的要点之一。事实上,该书的第二章全部都在讨论使用 Final 来促进优化和防止逻辑错误。 由于这个原因,静态分析工具(例如 PMD 和 Eclipse 的内置 SA)会标记此类情况。
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.
我个人的看法是这是浪费时间。 我认为视觉混乱和增加冗长是不值得的。
我从来没有遇到过这样的情况:我错误地重新分配了一个变量(记住,这不会使对象变得不可变,这意味着你不能重新分配另一个对变量的引用)。
但是,当然,这都是个人喜好;-)
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
将参数设置为最终保证方法中任何位置使用的值都引用传递的值。 否则,您必须在心里解析给定位置上方的所有代码,以了解该参数在该点的值。
因此,不使用final会使你的代码本身的可读性和可维护性降低:)
Final局部变量取决于意图,在我看来不太重要。 取决于发生了什么。
Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.
Hence, not using final makes your code less readable, and maintainable, all by itself :)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
对于局部变量,我倾向于避免这种情况。 它会导致视觉混乱,并且通常是不必要的 - 函数应该足够短或集中于单一影响,以便让您快速看到您正在修改不应该修改的内容。
对于幻数,我无论如何都会将它们作为恒定的私有字段而不是放在代码中。
我只在必要的情况下使用final(例如,将值传递给匿名类)。
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.
In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.
I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
由于 Java 的“通过引用传递”行为的(偶尔)令人困惑的本质,我绝对同意最终确定参数var。
在我看来,最终确定本地变量似乎有点矫枉过正。
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
做吧。
这是关于可读性的。 当您知道变量被分配一次且仅一次时,就更容易推断出程序的可能状态。
一个不错的选择是在分配参数或多次分配变量(循环变量除外)时打开 IDE 警告。
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
Final 有三个很好的理由:
就像方法一样,局部变量和参数不需要声明为final。 正如其他人之前所说,这会使代码变得混乱,可读性降低,而编译器性能优化的努力却很少,这对于大多数代码片段来说并不是真正的原因。
final has three good reasons:
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
尽管它会造成一些混乱,但值得将其放在
final
中。 如果您将其配置为这样做,例如 eclipse 可以自动放置final
。Although it creates a little clutter, it is worth putting
final
. Ides e.g eclipse can automatically put thefinal
if you configure it to do so.如果您想将这些参数传递给匿名类,那么将局部变量和方法参数设置为
final
至关重要 - 就像您实例化一个匿名线程并希望在 run() 方法体中访问这些参数一样。除此之外,我不确定通过编译器优化获得更好的性能是否会带来性能优势。 是否要优化它取决于特定的编译器实现...
了解使用
final
的任何性能统计数据将会很好...Making local variables and method parameters
final
is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using
final
...你为什么想要这么做? 您编写了该方法,因此任何修改它的人都可以始终从 qwerty 中删除 Final 关键字并重新分配它。 至于方法签名,同样的推理,虽然我不确定它会对你的类的子类做什么...它们可能会继承最终参数,即使它们覆盖该方法,也无法取消 x 的最终化。 尝试一下,看看是否有效。
那么,唯一真正的好处是,如果您使参数不可变并将其传递给子项。 否则,您只是在没有特别充分的理由的情况下使代码变得混乱。 如果它不会强迫任何人遵循您的规则,那么您最好留下一个好的评论,说明为什么您不应该更改该参数或变量,而不是给出最终修饰符。
编辑
作为对评论的回应,我将补充一点,如果您发现性能问题,将局部变量和参数设置为 Final 可以让编译器更好地优化您的代码。 然而,从代码不变性的角度来看,我坚持我原来的说法。
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
当它们在匿名类中使用时,我让 Eclipse 为我做这件事,由于我使用 Google Collection API,匿名类正在增加。
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
如果我们认为局部变量不会被重新分配或不应该被重新分配,我们在这里对它们进行处理。
这些参数不是最终的,因为我们有一个 Checkstyle-Check 来检查重新分配参数。 当然,没有人愿意重新分配参数变量。
We do it here for the local variables if we think they will not be reassigned or should not be reassigned.
The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.