Suppose I have a class Foo
, with a private variable bar_
containing some state for Foo
. If necessary, I may write public get/set metho
This is a matter of opinion, and a matter of judgement, but in general the interior of your Foo
methods are within the encapsulation you're trying to maintain, and so it is entirely reasonable for them to access bar_
directly. They are all in the same location, and so if you change the interior representation of your class to remove bar_
, you can easily find all of the uses to change as well.
There are justifications for using get/set functions internally in large classes, especially where bar_
is something that's not a key piece of the class's implementation design and could conceivably be changed without affecting the rest of it much. However, in many cases if you are changing the internal representation in such a way that bar_
no longer exists and its corresponding get_bar()
is computed, you will almost certainly want to revisit the internal usage to determine whether you want to refactor it so that it doesn't do that computation or does it differently.
With that said, speed is not a justification for not doing it -- but the comprehensibility cost of too many layers of encapsulation are; a forty-line class should not be complicated with additional internal encapsulation unless it's one of the cases where the encapsulation actually simplifies the code.
Edit: Also, ehdv raises an important issue that I missed: If you anticipate derived classes that override this piece of the internal representation, using get/set functions can make that overriding easier to do consistently. So that can be another factor in the decision.