« A hidden gem... or two Some notes on overriding "toString" »

January 09, 2004

Getters and setters are evil

Just came across this link today on Java World. The article is already 4 months old, but the points are still valid.

Basically, one of the four fundamental principles of OOP is data abstraction. As you know, data abstraction is the process of not exposing any of the "dirty details" of how the class works to those using the class (focusing on the "what" not the "how"). Users of the class have access to the public methods, and as long as those methods stay the same the internal implementation can be changed at will without effecting the end-user.

By having getters/setters for every private variable, you're exposing details about how the class is implemented. When people use getters/setters for your private variables, it becomes hard for you, the class creator, to change your implementation without breaking the public interface.

However, there are plenty of times where getters/setters (either via methods, or via properties) are necessary. These times might include things like checking on the status of an object, settings flags/parameters, etc... but maybe we have been too liberal with getters/setters by over-using them in situations when they're not entirely necessary?

Definitely a worthwhile read.

Comments

  • The question then is why would you have to modify your class when modifying an OO app? Shouldn't the structure of your application allow for enhancements based on a more modular approach, so that additional pieces of functionality are created outside your core classes and not within?

    To me that is the promise of OO, that you can approach coding thorugh a modular fashion and that the days of tinkering with your old code to either add or enhance functionality are over.

    I think it comes down to an architecture question...

    In addition an OO app should be flexible enough to allow developers to use your class without restriction (how can a developer predict what uses core functionality will have in 5-6 years)

    Cheers

  • There is a new post here, http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html, that continues the discussion about evil getters and setters. While I found that article very informative, it really made me re-think the way I have done things in the past, it appears that the decoupled architecture would prevent the current Swing event architecture from being driven by changes in the data.

    I know that one-off displays of data are fine in the Web Services domain, but what about those of us that are still programming for the desktop. Where users expect data to be updated in a timely manner. I'd hate to have to re-create and then re-add a panel everytime an employee got a pay raise just to update the new number. I guess I just don't see how to effectively tie an event mechanism into this paradigm.