Search code examples
c++oopcoding-styleencapsulationgoogle-style-guide

Why does Google name accessors and mutators after member variables?


http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Function_Names#Function_Names

Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().

Isn't it the whole point of encapsulation to hide implementation details from the user so he/she is not aware of whether the accessor/mutator method returns/modifies a member variable or not? What if I change the variable name or change the way it's stored inside the object?

EDIT:

If I have an instance variable int foo_ it seems straightforward

int foo() const { return foo_; }

but if I add another method that returns foo_ + 2, should I name if bar or GetBar?

int bar() const { return foo_ + 2; }
int GetBar() const { return foo_ + 2; }

If I choose GetBar and later decide to cache the returned value in another member variable bar_, will I have to rename the method to bar?


Solution

  • Actually, the point of encapsulation is to hide the inner workings of a class, not necessarily to hide the names of things. The name of the member variable doesn't matter; it's the level of indirection that the accessor or mutator provides.

    Having an accessor gives you the ability to change the inner workings of the class (including the names of member variables) without breaking the class's interface with the outside world. The user of the class need not concern himself with implementation details, including what things are named inside the class, but only on the behavior of the class, as seen from the outside.

    To put it another way, users of a class should not rely on Google's style guide to determine whether or not they are modifying a member variable.