简体   繁体   English

私人获取者和二传手-良好的实践?

[英]private getters and setters - good practise?

Is using private getters and setters for every private field in general considered as good practise? 一般而言,是否将private和设置器用于每个私有领域都被认为是一种好习惯? I know sometimes there are in some cases obvious benefits (against direct access to particular field), but it's enough to use private getters/setters always? 我知道有时在某些情况下(相对于直接访问特定领域)有明显的好处,但是始终使用private者/设置者就足够了吗?

You could use private setter & getters for private fields if you want to restrict accesiblity of private fields in class only and there is something you want to encapsulate around accessing it within class 如果您只想限制类中私有字段的可访问性,并且可以在类中访问某些封装内容,则可以对私有字段使用私有设置器和获取器

which is not generally the case 通常情况并非如此

除非您在标准的get / set之外进行额外的计算和过滤,否则我根本看不到这有什么用。任何有权访问私有方法的代码都将同样可以访问私有实例变量,所以你什么也没保护

The whole point of getters and setters is to provide clients of your class some measure of access to its internals. 获取器和设置器的全部重点是为您班级的客户提供某种访问其内部的方法。 Why on earth would such methods be useful when the class has direct access to its own private member variables? 当类直接访问其私有成员变量时,为什么这样的方法有用呢?

So if you implemented private getters/setters, the class could easily circumvent them and render them meaningless. 因此,如果您实现了私有获取器/设置器,则该类可以轻松绕开它们并使它们毫无意义。

At least in Scala you have the notion of object-private vs. class private, where this kind of discussion starts to be a little more useful. 至少在Scala中,您有对象私有和类私有的概念,这种讨论开始变得更加有用。

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

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