Why Should You Use Getters and Setters?

Some people aren’t very fond of accessors and mutators. On the surface they seem like needless functions, a waste of code when a simple class.variable would suffice. Some variables really are better off being set with variable = foo than with a mutator. On the other hand, other data types have such complex initialization procedures it’s easier to pass values into a mutator. C++’s maps are a good example of this kind of situation. Which is easier, std::map.insert(std::pair<Foo, Bar>(var1, var2)); or SetMap(var1, var2);?

Getters and setters don’t just make code easier to read, they also help tighten up abstractions. Implementation is hidden as much as possible when mutators are used. All that is exposed is a data type which may or may not be the same way the value is being stored. The user only sees a representation of that value. If you decided to change the implementation of a variable it would be easier to attempt to maintain an accessor/mutator interface than to have to change every line that uses the variable.

Mutators allow the programmer to control how variables change. A variable should not be set to a value which will break or work incorrectly with other code. Mutators can act as a filter to remove or correct values which would be unacceptable in the rest of the program.

Getters and setters can do more than just get and set variables. Mutators and accessors also allow the programmer to control when and if variables are changed. By only writing an accessor function variables can be read-only. It probably wouldn’t be very useful, but the same is true for only including a mutator; variables can also be write-only. A simple if-statement would allow a variable to be write-once. If the variable is anything other than the default value, input is discarded or the problem is brought to the attention of the programmer.

Accessor and mutator functions can be useful in many situations. In some circumstances they might just get in the way, but maintaining a clean interface for the future outweighs the slight inconvenience. Functions are powerful weapons in the war against leaky abstractions and bad code. They shouldn’t be put aside because they seem useless or are inconvenient to write.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s