Why getter/setter functions are evil

Why getter/setter functions are evil

Interesting article on why you shouldn’t be using getter/setter functions on your classes when programming.

The lack of getter/setter methods doesn’t mean that some data doesn’t flow through the system. Nonetheless, it’s best to minimize data movement as much as possible. My experience is that maintainability is inversely proportionate to the amount of data that moves between objects. Though you might not see how yet, you can actually eliminate most of this data movement.

By designing carefully and focusing on what you must do rather than how you’ll do it, you eliminate the vast majority of getter/setter methods in your program. 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. Most accessors find their way into code because the designers weren’t thinking about the dynamic model: the runtime objects and the messages they send to one another to do the work. They start (incorrectly) by designing a class hierarchy and then try to shoehorn those classes into the dynamic model.

This spawned an interesting conversation with a coworker who was usually against such meta-designing of code (i.e. designing the design). His point was that folks usually spend too much time futzing around getting the coolest language features into something instead of writing the fast code that actually solves the problem and you move on.  Complexity breeds unmaintainability, delays in development, difficulty in using/extending, and longer time for bug fixes.

I agreed with him on those points – I hate overly complicated code.  Much as I have use them on occasion (for collections) – I argue that heavily templated C code is always an order of magnitude harder to figure out/debug/learn than just straight C++.  Good code is the code that not only gets what you need done correctly, but is easy to maintain, read, understand, and train others on.  And the point of this guy’s article echos that.

My take-away point is that to a way to avoid complexity and increase performance – design your classes such that data doesn’t move around.  Just as in engines, the more moving pieces, the more likely a failure.  So if you are just sending requests around instead of the data; you’re much less likely to have failures and I would argue your code will be cleaner, simpler, and faster.  In graphics (and many other apps) moving blobs of vertex or other data around is expensive and should be minimized as much as possible.  This is a good way to think about classes in order to help you do that.

Leave a Reply

Your email address will not be published. Required fields are marked *