为什么要在 Java 中将局部变量和方法参数标记为“final”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/316352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why would one mark local variables and method parameters as "final" in Java?
提问by Julien Chastang
In Java, you can qualify local variables and method parameters with the final keyword.
在 Java 中,您可以使用 final 关键字来限定局部变量和方法参数。
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.
这样做会导致无法在方法主体中重新分配 x 和 qwerty。
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?
这种做法将您的代码推向不变性的方向,这通常被认为是一个优点。但是,它也往往会使代码变得混乱,“最终”无处不在。您对 Java 中局部变量和方法参数的 final 关键字有何看法?
采纳答案by rjray
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.
您应该在适当的时候尝试这样做。除了在您“不小心”尝试修改值时发出警告外,它还向编译器提供信息,可以更好地优化类文件。这是 Robert Simmons, Jr 所著的“Hardcore Java”一书中的要点之一。事实上,这本书的第二章全部都在使用 final 来促进优化和防止逻辑错误。出于这个原因,诸如 PMD 和 Eclipse 的内置 SA 之类的静态分析工具会标记这些类型的情况。
回答by SCdF
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 ;-)
但是,当然,这都是个人喜好;-)
回答by Elie
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.
你为什么要?您编写了该方法,因此任何修改它的人都可以始终从 qwerty 中删除 final 关键字并重新分配它。至于方法签名,同样的推理,虽然我不确定它会对你的类的子类做什么......它们可能会继承最终参数,即使它们覆盖该方法,也无法取消最终确定 x。尝试一下,看看它是否有效。
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.
在回复评论时,我会补充说,如果您看到性能问题,将局部变量和参数设为 final 可以让编译器更好地优化您的代码。但是,从代码的不变性的角度来看,我坚持我原来的说法。
回答by javamonkey79
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
由于 Java 的“通过引用传递”行为的(偶尔)令人困惑的性质,我绝对同意最终确定参数 var。
Finalizing local var's seems somewhat overkill IMO.
完成本地变量似乎有点矫枉过正 IMO。
回答by Uri
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).
我只在必要的情况下使用 final(例如,将值传递给匿名类)。
回答by Miserable Variable
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.
当它们在匿名类中使用时,我让 Eclipse 为我做这件事,由于我使用 Google Collection API,这种情况正在增加。
回答by boutta
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.
参数不是最终的,因为我们有一个 Checkstyle-Check 检查重新分配参数。当然,没有人会想要重新分配参数变量。
回答by Arne Burmeister
final has three good reasons:
final 有三个很好的理由:
- instance variables set by constructor only become immutable
- methods not to be overridden become final, use this with real reasons, not by default
- local variables or parameters to be used in anonimous classes inside a method need to be final
- 构造函数设置的实例变量只会变得不可变
- 不被覆盖的方法成为最终的,使用它有真正的原因,而不是默认
- 要在方法内的匿名类中使用的局部变量或参数需要是最终的
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。正如其他人之前所说的那样,这会使代码变得混乱,而编译器性能优化的努力却很少,这对于大多数代码片段来说并不是真正的原因。
回答by Craig P. Motlin
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.
一个不错的选择是在分配参数或多次分配变量(不是循环变量)时打开 IDE 警告。
回答by Thorbj?rn Ravn Andersen
Making a parameter final guaranteesthat 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, notusing final makes your code less readable, and maintainable, all by itself :)
因此,不使用 final 会使您的代码本身的可读性和可维护性降低:)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
最终局部变量取决于意图,在我看来并不重要。取决于发生了什么。