Search code examples
encapsulationgetter-setterprivate-members

Getters and setters for private helper methods


I have a theoretical question about the use of getters and setters.

Say in a class I have a private variable and a private helper method. If the private method accesses a private variable within the class, is it really necessary for it to do so via a getter/setter method?

My thinking is that for this one special case (since the private method can't be accessed from outside of the class), that not using getters and setters and instead just "reaching in" directly would not be a violation of encapsulation. Is that true?

Thanks


Solution

  • The purpose of using getters and setters is to provide a public interface for people who want to use your class so that you're free to manipulate your internal implementation without changing the interface.

    If you're manipulating private variables inside a private helper method, there's really no front-facing "interface" involved at any point. You may want to use a getter or setter if accessing or changing a value is supposed to cause side effects (so you don't have to remember to constantly update any auxiliary values), but it would be overkill in the general case.