Search code examples
oopencapsulation

When should a class use its own getters/setters vs accessing the members directly?


When generating setters and getters in Eclipse one of the options is to use the getters and setters within the class rather than accessing the class members directly. Is this level of class internal encapsulation useful or is it taking a good idea one step too far?


Solution

  • I think it's a good idea if you want the potential side-effects to occur - validation, logging etc. (In C# I'd like to be able to declare a variable and property and say that the only access to the variable is through the property.)

    Occasionally you may well find you need to set the variable directly precisely because you don't want the side-effects. For instance, you may need to set two variables together, and both the "before" and the "after" states are valid, but setting either property individually would make validation blow up.