在 Java 中适用时使用“final”修饰符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/137868/
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
Using the "final" modifier whenever applicable in Java
提问by surajs
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.
在 Java 中,有一种做法是声明每个变量(本地或类),如果它们确实是最终参数,则它们是最终的。
Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.
虽然这使得代码更加冗长,但这有助于轻松阅读/掌握代码,并且由于意图明确标记,还可以防止错误。
What are your thoughts on this and what do you follow?
你对此有什么想法,你会遵循什么?
采纳答案by Johan Pelgrim
I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final
modifiers anywhere, but when you think about it...
我认为这一切都与良好的编码风格有关。当然,您可以final
在任何地方不使用大量修饰符的情况下编写好的、健壮的程序,但是当您考虑...
Adding final
to all things which should notchange simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.
添加final
所有不应更改的内容只会缩小您(或下一个正在处理您的代码的程序员)误解或误用导致您的代码的思维过程的可能性。至少当他们现在想要改变你以前不可变的东西时,它应该敲响一些钟声。
At first, it kind of looks awkward to see a lot of final
keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on(you can take it from me ;-)
起初,final
在你的代码中看到很多关键字看起来有点尴尬,但很快你就会不再注意到这个词本身,而是会简单地想,从这一点来看,这件事永远不会改变——在(你可以把它从我;-)
I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final
I'll do it.
我认为这是一个很好的做法。我不是一直在使用它,但是当我可以并且标记某些东西时final
我会这样做。
回答by SCdF
I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.
我从来没有遇到过在变量上使用 final 关键字阻止我犯错误的情况,所以目前我认为这是一种巨大的浪费时间。
Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.
除非有真正的理由这样做(因为你想对那个变量是 final 提出一个具体的观点)我宁愿不这样做,因为我发现它使代码的可读性降低。
If, however, you don't find it makes the code harder to read or longer to write then by all means go for it.
但是,如果您没有发现它使代码更难阅读或更长的时间编写,那么请务必使用它。
Edit:As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:
编辑:作为澄清(并试图赢得反对票),我并不是说不要将常量标记为最终,我是说不要做这样的事情:
public String doSomething() {
final String first = someReallyComplicatedExpressionToGetTheString();
final String second = anotherReallyComplicatedExpressionToGetAnother();
return first+second;
}
It just makes code (in my opinion) harder to read.
它只会让代码(在我看来)更难阅读。
It's also worth remembering that allfinal does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.
这也是值得记住的是,所有的最终作用是阻止你重新分配一个变量,它不会让一成不变的或类似的东西。
回答by HowardSP
You really need to understand the full use of the final keyword before using it. It can apply to and has differing affects on variables, fields, methods and classes
在使用 final 关键字之前,您确实需要了解它的完整用法。它可以应用于变量、字段、方法和类,并对其产生不同的影响
I'd recommend checking out the article linked to below for more details.
我建议查看下面链接的文章以获取更多详细信息。
回答by jjnguy
I hardly use final on methods or classes because I like allowing people to override them.
我很少在方法或类上使用 final,因为我喜欢允许人们覆盖它们。
Otherwise, I only use finally if it is a public/private static final type SOME_CONSTANT;
否则,我只使用 finally 如果它是 public/private static final type SOME_CONSTANT;
回答by Lars Westergren
Effective Java has an item that says "Favour immutable objects". Declaring fields as final helps you take some small steps towards this, but there is of course much more to truly immutable objects than that.
Effective Java 有一个条目,上面写着“Favor immutable objects”。将字段声明为 final 可以帮助您为此采取一些小步骤,但对于真正不可变的对象来说,当然还有更多。
If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs.
如果您知道对象是不可变的,则可以在多个线程/客户端之间共享它们以进行读取而无需担心同步,并且更容易推断程序如何运行。
回答by Omnipotent
Final when used with variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-)
在 Java 中与变量一起使用时 Final 提供了 C++ 中常量的替代品。所以当 final 和 static 用于变量时,它变得不可变。同时让迁移的 C++ 程序员非常高兴 ;-)
When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated.
当与引用变量一起使用时,它不允许您重新引用该对象,尽管该对象可以被操纵。
When final is used with a method, it does not allow the method to be over-ridden by the subclasses.
当 final 与方法一起使用时,它不允许子类覆盖该方法。
Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism.
一旦用法很清楚,就应该谨慎使用。这主要取决于设计,因为在方法上使用 final 无助于多态性。
One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int COLOR_RED = 1; (Upper case seperated by underscore)
只有当您确定变量的值将/不应该更改时,才应该将它用于变量。还要确保您遵循 SUN.for 鼓励的编码约定,例如:final int COLOR_RED = 1; (下划线分隔的大写字母)
With a reference variable, use it only when we need a an immutable reference to a particular object.
对于引用变量,仅当我们需要对特定对象的不可变引用时才使用它。
Regarding the readability part, ensue that comments play a very important role when using the final modifier.
关于可读性部分,确保注释在使用 final 修饰符时起着非常重要的作用。
回答by Hans Sjunnesson
Using anonymous local classes for event listeners and such is a common pattern in Java. The most common use of the final keyword is to make sure that variables in scope are accessible to the even listener.
将匿名本地类用于事件侦听器,这是 Java 中的常见模式。final 关键字最常见的用途是确保偶数侦听器可以访问作用域中的变量。
However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong.
但是,如果您发现自己需要在代码中放入很多最终语句。这可能是一个很好的提示,你做错了什么。
The article posted above gives this example:
上面发布的文章给出了这个例子:
public void doSomething(int i, int j) {
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};
}
回答by anjanb
I use it for constants inside and outside methods.
我将它用于方法内部和外部的常量。
I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons).
我只是有时将它用于方法,因为我不知道子类是否不想覆盖给定的方法(无论出于何种原因)。
As far as classes, only for some infrastructure classes, have I used final class.
至于类,仅针对某些基础结构类,我使用了最终类。
IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well.
如果将函数参数写入函数内部,IntelliJ IDEA 会发出警告。所以,我已经停止使用 final 作为函数参数。我也没有在 java Runtime 库中看到它们。
回答by Pawe? Hajdan
Using final for constantsis strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes testingharder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a mockimplementing the same interface.
强烈鼓励对常量使用 final 。但是,我不会将它用于方法或类(或者至少考虑一下),因为它使测试变得更加困难,如果不是不可能的话。如果您绝对必须将一个类或方法设为 final,请确保该类实现了某个接口,这样您就可以有一个实现相同接口的模拟。
回答by Bruno De Fraine
The final
modifier, especially for variables, is a means to have the compiler enforce a convention that is generally sensible: make sure a (local or instance) variable is assigned exactly once (no more no less). By making sure a variable is definitely assigned before it is used, you can avoid common cases of a NullPointerException
:
该final
修改,特别是变量,是一种手段,让编译器强制执行约定,一般是明智的:确保(本地或实例)变量分配一次(不多不少)。通过确保在使用变量之前明确分配了变量,您可以避免 a 的常见情况NullPointerException
:
final FileInputStream in;
if(test)
in = new FileInputStream("foo.txt");
else
System.out.println("test failed");
in.read(); // Compiler error because variable 'in' might be unassigned
By preventing a variable from being assigned more than once, you discourage overbroad scoping. Instead of this:
通过防止变量被多次分配,您可以阻止范围过宽。取而代之的是:
String msg = null;
for(int i = 0; i < 10; i++) {
msg = "We are at position " + i;
System.out.println(msg);
}
msg = null;
You are encouraged to use this:
鼓励你使用这个:
for(int i = 0; i < 10; i++) {
final String msg = "We are at position " + i;
System.out.println(msg);
}
Some links:
一些链接:
- The final story(free chapter of the book "Hardcore Java")
- Some final patterns
- Definite assignment