To bean or not to bean
The problem
Recently I came over “The Magic Setter Antipattern” article on DZone I tend to disagree. It proposes to use direct field access instead of getters and setters.
I still think that getters and setters are good idea (yet the one that requires a little too much boilerplate code in Java), and here is why.
1. Libraries
JavaBeans is a standard. While a lot of libraries can work with fields too, you will never know which one would fail to access the fields directly.
2. Abort early
While having side effects in the setter code is a wrong thing, there are a number of a perfectly reasonable use cases to code in you setter. One of them are simple validations. If you have your validation in the setter, you will immediately see what code is trying to set incorrect value. Any subsequent validation code would not give you this information.
3. Full JavaBeans bells and whistles
Do you know that JavaBeans are not only getters and setters? For example, one of the features is a PropertyChangeListener. And you can’t implement this without having a setter.
Note that you should be careful for not to throw a lot of synchronous code into your listeners or it will become a monster.
4. Another simple code to react for property change
Actually there can be tons of legitimate things to do in your setters, like logging or plain change counter increase. Main things to consider are:
Are there any side effects? If there are, you should probably do it in some other way.
Is this a plain data bean or even DTO? If it is, it should not have much logic or external references. But not all beans are data beans.
5. Interfaces
You can’t expose your field through the interface. Period. One can argue that you are exposing a business method, but it’s not always true. Sometimes it’s a setter or (more often) a getter.
6. Consistency
Primary argument in the original article is YAGNI. My answer is that you must be consistent and use only one method (field or setter/getter access) in your application. If you need some logic in some of the field access, you must use getters and setters everywhere. Otherwise you will be easily lost in what to use where.
7. Refactoring cost
Again, let’s say you used fields access and now you need a piece of logic for this getter. While current IDEs do a decent job in refactoring, encapsulating a field can be very error prone, given how often it’s accessed with different methods, including libraries/ELs.
Conclusion
Well, you saw my arguments. Feel free to comment, argue and make your decision. My decision is to continue with getters/setters pattern.











