Calling this->get/this->set methods versus directly accesing member variables in C++

前端 未结 8 637
挽巷
挽巷 2021-01-18 18:21

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

8条回答
  •  再見小時候
    2021-01-18 19:09

    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.

提交回复
热议问题