简体   繁体   English

如果getter返回可变对象的副本,是否需要在不可变的类中设置最终实例变量

[英]Is it required to set final instance variables in immutable class if copy of mutable objects is returned by getters

如果没有公共设置器和私有访问权,在创建不可变类时是否需要将实例变量声明为final?

It is not required, as in the compiler won't compile if you don't. 它不是必需的,因为如果不这样做,在编译器中将不会编译。 But if the variable is immutable, adding final will make your intent clear to other programmers (and yourself when you look at the code again tomorrow and wonder about it), may help the compiler generate more efficient code and will make the compiler complain if later on you do try to change the variable, which may be helpful of course and may indicate that the code change is maybe not ideal, and that you should think of an alternate solution. 但是,如果变量是不可变的,则添加final将使您的意图向其他程序员(和您自己,明天再次查看代码并对此感到疑惑时)清晰明了,可能有助于编译器生成更有效的代码,并使以后编译器抱怨您确实尝试更改该变量,这当然可能会有所帮助,并且可能表明代码更改可能不是理想的选择,您应该考虑一种替代解决方案。

No, it is not required: since the private variables are not accessible from subclasses, your class would remain immutable as long as your own code does not violate the immutability rule. 不,这不是必需的:由于不能从子类访问私有变量,因此只要您自己的代码不违反不变性规则,您的类就将保持不变。

This said, it is certainly a good thing to mark these variables final to protect your code from mistakes of someone else * maintaining your code. 这就是说,将这些变量final标记为保护您的代码免受他人*维护您的代码的肯定是一件好事。

* or even your own mistakes two years from now, when you forget a lot of the details about your class. *甚至是两年后您自己的错误,那时您忘记了有关课堂的许多细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM