Monday, November 15, 2010

Setters and Getters Are Evil

There are a lot of things I like about Java, but one thing I dislike is the way it pushed Getters and Setters. With Beans and tools that use them like GUI builders, Java really encourages one to write getters and setters. This seems to have resulted in the practice of providing getters and setters by default, even to the point where IDEs will auto generate them for you.

This is BAD! It promotes lazy object oriented coding. Rather than thinking about what interface should be presented to the world, it is too easy just to provide access to all of the internal fields via getters and setters. Who needs Data Hiding anyway? When you are in the habit of writing getters for all your fields, it is unlikely that you are actually decoupling your components.

Even worse than the getters are the setters. When you have setters it is hard to enforce class invariants. Worse, you lose all the advantages of  making an immutable class. Often times setters are created out of laziness as well. Have you ever had a class that had a lot of properties that needed to be set, but then was never changed? This seems to be a common occurrence. (Almost) no one likes to create constructors with a lot of arguments, and sometimes it is just easier and cleaner to write the code with setters. You tell yourself that you'll never use the setters except at construction time, but what if you forget or another developer joins the project? It's easy to just create setters, but it is better to avoid it, potentially by creating a special purpose configuration class.

¡Viva la Revoluci√≥n!
I realize that this is a lost cause because too many people and tools rely on setters and getters, but I'll fight it anyway. Next time you create a setter or a getter please do me (and anyone who might have to maintain your code) a favor, and consider very carefully whether it is really a good idea.

No comments: