简体   繁体   中英

private getters and setters - good practise?

Is using private getters and setters for every private field in general considered as good practise? 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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