Over a million developers have joined DZone.

Getters are an Antipattern?

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

When you realize that property setters is an antipattern, because you want to protect the status of your entity from direct external manipulation, the next step is starting to believe that even Getters can be considered an Antipattern.

This is some sort of extreme object oriented thinking, because getters does not modify the status of an object, so there is nothing evil in them… or not? If you look for the definition of Encapsulation from Wikipedia you can find this:

encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition. Typically, only the object’s own methods can directly inspect or manipulate its fields.

If you read it carefully you can find that a well encapsulated object completely hides his status from the external world. One of the most interesting reason why you should avoid external world to read your internal status with getter is avoiding other object to do logic that belong to you. Whenever an object expose, even in read-only, part of its internal status, there is the risk that some other object uses that status to implement some logic and this is bad for many reasons.

First of all this is a symptom that logic is probably not in the right place. If you need to know the internal status of another object to implement something, probably that logic should be in other object.

Another drawback is that objects become to be too much entangled, when you modify the status of an object, if it is completely hidden to the outside world, you need only to take care on the logic inside the object; on the contrary, if the status is exposed with getters, you need to search all the usage of the status before modification.

This does not mean that you should use no getters whatsoever, but you surely need to think twice when you want to expose some part of the status, even if in read-only.

Gian Maria.


From http://www.codewrecks.com/blog/index.php/2011/12/16/getters-are-an-antipattern/

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}