Why getter and setter methods are evil

I just stumbled upon a very interesting article about object-oriented design that I’ve been shown back when I started working at Daedalic Entertainment. In this article, Allen Holub shows why a high number of accessor methods might indicate that your application is not well-designed from an object-orientated perspective, and he teaches you how to avoid these methods. If you’re about to stop reading right now, please try and remember at least one important rule:

“Don’t ask for the information you need to do the work; ask the object that has the information to do the work for you.”

In case you’re still with me, here’s the long answer to the question why getter and setter methods are evil:

In object-oriented systems, no class should expose any of its implementation details. Take, for instance, a class that features a getter method called getCount(). Let’s assume that your system contains about 1,000 calls to that method and tries to store the return values in local variables. If for some reason the type of the return value was int, and has to be changed to long now, then… whooops. You’ll get 1,000 compile errors.

Holub states that “getter and setter methods […] are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details.” If in turn your system is well-designed, you’ll be able to make massive changes to your classes. You could even trash whole parts of your application and replace them with a completely different kind of implementation.

This immediately leads to the question: “When is an accessor okay?”

First, methods who return interface references are fine of course – interfaces hide the implementation details of the classes whose instances might be returned by the method. According to Holub, these methods are not really accessor methods in terms of getters that provide access to a private field.

Second, it’s hard to get rid of all accessors if you don’t know in advance how your class will be used. This is the reason why you’ll still find many getters in the Java API, for example – but it isn’t an excuse for being lazy designing your own system. In most cases, you do know how you’ll use your classes.

Check out the original article if you’re interested in an in-depth look at the nature of object-oriented design, data abstraction and more detailed examples of how to develop your own design strategy.

Author: npruehs

Nick Pruehs is a Co-Founder of Slash Games, Hamburg. In 2009, he graduated as “Best Bachelor” in computer science at Kiel University. Two years later Nick finished his master’s degree in “Sound, Vision, Games” at Hamburg University of Applied Sciences, becoming the Lead Programmer of Daedalic Entertainment shortly after.

Questions? Comments? Suggestions? Your turn! :)