Adam Bien's Weblog
Getters and setters: an antipattern. JavaBeans and OO
As I saw the first time getters and setters in C++, I was a little bit confused and also disappointed. The encapsulated state, was indirectly exposed via the property accessors. Everyone told me: you have to design your classes this way, because you can then intercept the call and provide some additional value or protect the variables. In 99% of all getters/setters cases nothing happened, so it is a kind of overengineering. It becomes even worse. Using getters and setters it is hard to ensure the consistency of an object. Actually you have to wait until alls setters are invoked, before the object is usable. So it requires an insider knowledge what an object needs. Sample:
So in the OO-style you do not even know, whether the object has a private state, or not. It simple connects as expected - no magic here. Either an exception is thrown or not. So the consistency can be better assured. It is also more expressive: the "parameters" are bound to the activity.
JavaBeans were invented to support better IDE integration and be machine-readible. But it is not a great idea to use the default getter/setter approach to create business applications or domain models. From my point of view, using getters and setters is only a work around. In J2EE 1.4 world this conventions were needed to create transfer objects (or Value Objects). The design of many applications today becomes more and more procedural. It is nothing wrong with it - but with "real" objects more maintainable applications can be build...
Conclusion: The getter and setter convention increases the reflection capabilities so it is especially useful for machines (IDEs, framework). In standard OO-design property accessors are more an antipattern than a best practice. So you should be careful with the "Generate getters and setters" wizzards in modern IDEs...
NEW workshop: Microservices with Java EE 7 and Java 8, January 26th, 2015, Airport Munich