0

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

1
  • As a non-language-specific coding style question which may generate controversy, this question might be better suited for programmers.stackexchange.com. Commented Nov 16, 2013 at 7:10

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

No, if I understand your question correctly. A method has access to private members of the class, regardless of whether it is public or private. To clarify, the following are both legal in C++:

class MyClass { private: Method1() {member = 0;} public: Method2() {member = 1;} private: int member; } 

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?

If you are still referring to the method, which is a member of the class, then no, it won't be. If you are referring to a function that is not a method of that class, then yes, you would not be allowed to access those private members unless the function was declared as a friend in the class in question.

This is all with regards to C++ of course.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.