Reputation: 1338
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?
Upvotes: 0
Views: 220
Reputation: 30310
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.
Upvotes: 0
Reputation: 3344
I can't see how this would be useful at all unless you're doing extra computation and filtering beyond standard get/set... Any code that has access to the private methods would have access to the private instance variable as well anyway, so you aren't protecting anything
Upvotes: 1
Reputation: 240966
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
Upvotes: 2