What are accessors and mutators?

Accessors and mutators are public member functions in a class that exists solely to set or get the value of a class member variable. They are often referred to as getter and setter or set and get functions. I will use the term setter for mutators and getter for accessors for this article.

Many programmers think why we should create getter and setter functions when we can declare public member variables and access them easily using the object of the class. But, there are many benefits from a software engineering point of view to create classes with only private member variables and use getters and setters to manipulate their values.

One of the primary benefits of object oriented design is combining the data and the methods that operate on them into a single component. This is referred to as encapsulation. It allows you to hide the actual implementation of the class from the users of the object. It allows the programmer to make changes in the hidden part of the class design without affecting the users of the objects derived from the class. So if you created some complex class and sold it to a bunch of other developers, you could make changes to your class to improve performance of the hidden part, and they would not have to rewrite their code to use newer versions.

Another crucial benefit of setter functions is that, you can validate the data before set the value. For example, we have created one class for accounting and let’s assume the maximum value for any transaction is 10000. With a public variable, there is no way to stop someone from setting this value to 20000.

Naming conventions

Typically, programmers name getter functions as “get” followed by the name of the variable being accessed and setter functions as “set” followed by the variable name.

Getters and setters in use

The example below adds getters and setters to our Accounting class.

class Accounting
{
private:
  int transactionLimit;

public:
  // setters
  bool setTransactionLimit(int);

  // getters
  int getTransactionLimit();
};

// Setter function perform input validation
bool Accounting::setTransactionLimit(int l) {
  if (l < 0 || l > 10000)
    return false;
  else {
    transactionLimit = l;
    return true;
  }
}

// Simple getter functions. This hide the 
// actual method of storage from object user.  
int Accounting::getTransactionLimit() {
  return transactionLimit;
}

In above class, the setter functions also validate the input and return true if the value is acceptable or false if not. In that way, the programmer using the class can know if the provided value is valid and write the code to respond in an appropriate manner.

Comments

comments