Richard Bucker

Getters and setters are STILL evil!

Posted at — Feb 14, 2012

I’m a 3rd party reading the source code of another 3rd party for a project I’m working on and I find my head spinning because the Class that I’m currently reading is 90% getters and setters. Of course I did a little googling in order to see what the current state of accessors was and that’s when I found this evil article. Looking at the byline I think it was written in 2003 and of course not much has changed since then.What troubles me about the article is that it nor any of the OO gurus ever discuss anything but the simplest OO objects like point, line, square, circle. Sure, when you have essentially 3 or 5 input values it’s simple to accept them in the constructor. But when you have 100 instance values of varying types then what? In the evil case getters and setters are used so that the data is validated during the set based not he rules of the class declaration. Using a single get/set does not give you that functionality and validating in the constructor makes the class unwieldy.With so many getters and setters there is so much static code that would need to be hand coded and the only shortcut would be calling the getters and setters with some reflection. Unfortunately that has other side effects when combining meta programming and OO.Personally I like the python approach of typeless data. Then I wrap the instance data in a hash called a dict in python. And then if I really need to validate the data it’s either done when the data enters or exits the system (using a userspace data type dict) or when constrained in the data store (DB).I’m just not a fan of the getter/setter. Too much code. Too little payback.