September 08, 2003
Getter and setter methods are evil

Why getter and setter methods are evil explains, uh, why getter and setter methods are evil. 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, it advises.

I hadn't really thought about this, but it strikes me as good advice. Looking through my own code, I see almost no simple setter methods, and few getters. I do use 'is' type getters fairly frequently, though. This feels OK to me.

This isn't the same thing as Python's reason for avoiding getters and setters, BTW. Python's descriptors mean that you can directly access object attributes without breaking encapsulation, making getters and setters very un-Pythonic.

Update September 9th: Having thought about this overnight, I'm a little concerned that this might be a bit too purist, a bit too principle of least privilege. Yes, so long as the designer of the class has anticipated every need that a client of the class might have, it's better to encapsulate firmly, and to prevent anything unanticipated from happening. In the real world, the designer hasn't thought of everything.

Have you ever raged that a method or attribute that you need to access has been marked private, because the designer of the class that you are using didn't anticipate your every need? I know I have.

Still, the designer should provide a named method for everything for which he/she does anticipate a need. Access to an object's attributes, be it via setters and getters. or directly, strikes me as a code smell.

Posted to Java by Simon Brunning at September 08, 2003 11:03 AM
Comments

Code smell is a good way to put it.

Getters and Setters are often indicative of "Data Transfer Objects." DTOs are devoid of business logic. They can be helpful where data needs to be marshalled for transport.

Unfortunately DTOs are often they indicative of an excessively layered architecture, typical of a modern J2EE system. In these systems, the bulk of the code is concerned with transforming data from one model to another and back again; for example SQL -> DataObject (a DTO) -> BusinessModelObject (another DTO) -> API Parameter Object (more DTOs) -> DisplayObject (still more DTO) -> Custom JSP Tag Models (DTOs(!)) -> HTML Page and back again. Even when written in Java, it still looks like COBOL.

Allen Holub was advocating careful consideration before layering your application in this way.

Posted by: Alan Green on September 9, 2003 02:02 PM

Posted by: Alina_m on October 30, 2008 06:46 AM

Posted by: Alina_m on November 4, 2008 10:22 PM

medical to school

Posted by: school rating medical on January 4, 2009 11:31 PM
Post a comment
Name:


Email Address:


URL:



Comments:


Remember info?