DIMAJIX - software consulting (http://www.dimajix.de/)
 

Access Functions

After we have seen that we should declare all member variables as private in most cases, there still is the question how to access these variables from outside the class. But before explaining the getter and setter-pattern for accessing member variables, we first should think about another question: Do we really want access to all member variables?

A common mistake for many beginners is to endow a class with getters and setters for every single member variable. This does not always make much sense, because again this would disclose the implementation to a certain degree. The correct approach when designing a class and its interface is to ask how the class is to be used. This means first you specify the methods of a class and then you add all member variables needed to implement these methods - after this step it is normally not necessary to add any additional getters or setters to the class.

You have to be especially careful with setters in complex classes and you have to take care that setting a single member variable does not lead to a inconsistency of the whole object. This may easily happen with more complex classes, because their member variables may have delicate dependencies on each other.

But for any member variables that should be modified directly, you should always provide a set of appropriate getters and setters.


Rule 40. Use getters and setters in order to access class member data.

As we already explained, you should avoid direct access to member variables in most cases, except for very simple fixed size container classes like complex numbers, vectors etc. All other member variables which are to be exposed have to be accessed by getters and setters, like in the following example

class Animal {
private:
    String          m_Name;
    String          m_Species;
    
public:
    inline const String& getName() const;
    inline void     setName(const String& );
    
    inline const String& getSpecies() const;
    inline void     setSpecies(const String& );
    
    ...
};

This practice allows easy modifications and insertion of checking routines, e.g. one could check in the example above if the given species is found in a dictionary containing all known species. This helps to find bugs easily and at an earlier stage of development. Many compilers offer special assert-functions that will perform a check and inform the debugger if a test has failed.


Rule 41. Access functions are to be inline.

Simple access functions, especially getters, should always declared inline. This helps to produce code that is as fast as if the member variables was specified public and accessed directly without any getter or setter.


Rule 42. getters are to be const-Functions.

Getters should never modify the state of an object, and thus they should be declared as const-functions, as seen in the example above.

Kaya Memisoglu 2005-01-06