Getters And Setters Redux
Is anything more hotly debated in OO development? Here's an article eloquantly arguing against them. Now, in the past, I have been strongly in the use getter/setters camp. Recently, I started to not use getters/setters to see if I got any new insights. At first, it felt weird and unnatural, but I soon got over that. I started to not use getters/setters for the exact reason listed in the article because I had seen too much code depend on the getters/setters and knowing too much about the internal representation of an object. Now, in java, you can restrict access to getters/setters through protected and private (which by the way, I think private is evil, but protected is broken as well...I think protected should only be used by the object and its inheritance heirarchy, but that's another discussion). I also wanted to not use getters/setters after watching the a Self video where they used methods and variables interchangebly. But, in most languages, there is a difference in calling a method and accessing a veriable. And that is the one thing I missed when I stopped using getters/setters, the consistency! In both java and Smalltalk, instance and local variable access looks identical and its easy to make a mistake (think a newbie or a really late night at work). So, am I saying that I think consistency is more important than encapsulation? NO! But, I do think they are equally important. You can achieve encapsulation with getters/setter by either restricting access (at the language level), placing them in a different spot in the source code (like at the bottom, make it hard to get to!), or through categories (I frequently put my getters/setters in an accessing/private category and never look at it unless I absolutely need it). You can even use method wrappers to make sure the sender is self and report otherwise. So, while I agree with the article, I still like to use getters/setters for the reason of consistency. I think it's up to a good programmer to keep encapsulation enforced. Oh, one more thing, one good reason for keeping your getters/setters is that if you ever need to do anything extra when an instance variable is set, you can do it through the setter and it's easy to add debug code in a getter (like a break point). I use my setters to ensure parent relationships are kept consistent (there's that word again!). Setters can also fire change events which are important for persistent frameworks and GUIs. One important thing that I am starting to realize with this debate is that it is a personal style issue of the programmer. Both sides have pluses and minuses and it's up to each shop/developer to make their choice. The worst is to mix both paradigms. Remember keep it consistent!