Public getters and setters should be considered as antipattern. Or more precisely: 95%-100% of all members should be completely hidden.
I got 24 comments for my last entry about "evil" getters and setters. The conclusion is interesting. Everyone agreed, that getters and setters do violate the encapsulation and so could be a maintenance problem.
Of course accessors are useful in infrastructure frameworks like EMF, XMLBeans, java.beans.XMLEncoder/Decoder etc. The main purpose of such frameworks is to provide additional services (serialization, delta computation, XML-representation etc.) based on the internal state of an object. So Getter and Setters are the easiest way in this infrastructural area to access the data.
But in business/domain applications getters/setters are an antipattern. So considering the fact I extracted the following best practices to deal with JavaBeans:
- Do not use getters and setters in business objects.
- Infrastructural code like Value Objects (throw-away) should be separated from the realization of the business logic.
- Use object oriented style whenever possible, instead invoking series of accessors.
- ...do not expose private state of an object using public accessors.
Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition
airhacks.fm the podcast:
Stay in touch: airhacks.news.