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
?
Mutators (setters) are used to set values of private data members. One of the main goals of a mutator is to check correctness of the value to be set to data member. A setter's name starts with set, followed by name of data member.
Accessor and mutator functions (a.k.a. set and get functions) provide a direct way to change or just access private variables. They must be written with the utmost care because they have to provide the protection of the data that gives meaning to a class in the first place.
In Java, mutator methods reset the value of a private variable. This gives other classes the ability to modify the value stored in that variable without having direct access to the variable itself. Mutator methods take one parameter whose type matches the type of the variable it is modifying.
Accessors and mutators are public member functions in a class that get (accessors) and set (mutators) the values of class member functions. In other words, these are functions that exist solely to set or get the value of a class member variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With