Avoid JavaBeans style of construction

Some argue that to construct a Model Object in many steps, first by calling a no-argument constructor, and then by calling a series of setXXX methods, is something to be avoided, if possible: Of course, JavaBeans follow this pattern of "no-argument constructor plus setXXX". However, JavaBeans were originally intended for a very narrow problem domain - manipulation of graphical components in an IDE. As a model for the construction of typical data-centric objects (Model Objects), JavaBeans seem completely inappropriate. One can even argue strongly that, for Model Objects, the JavaBeans style is an anti-pattern, and should be avoided unless absolutely necessary.

"The JavaBeans pattern has serious disadvantages." - Joshua Bloch, Effective Java


If you need more convincing, read on.

Here is the definition of a Java Bean, directly from the original specification:

"A Java Bean is a reusable software component that can be manipulated visually in a builder tool."

This is very clear and simple. No mention is made here, or anywhere else in the specification, of Model Objects used to encapsulate database records. The whole idea of a Model Object is entirely absent from the Java Bean specification, and for good reason: the manipulation of graphical controls and the representation of database records are unrelated issues.

The life cycle of a Java Bean, starting with its no-argument constructor, is derived mainly from the task of configuring a graphical control having some default initial state. For the intended domain, this is indeed a reasonable design. For Model Objects, however, the idea of configuration in this sense is entirely meaningless.

The role of a Model Object is to carry data. Since a no-argument constructor can only build an object that is initially empty, then it cannot contribute directly to this aim. It does not form a natural candidate for the design of a Model Object.

To put data into empty Java Beans, frameworks typically call various setXXX methods using reflection. There is nothing to prevent them from calling constructors in exactly the same way.

A demonstration that a framework does not need JavaBeans for its Model Objects is found in the WEB4J tool. WEB4J calls (surprise, surprise) a constructor to build Model Objects. It recommends implementing Model Objects as immutable objects, not Java Beans.

The widespread adoption of Java Beans as a supposedly appropriate design for Model Objects seems to be an error.

See Also :
Validate state with class invariants
Immutable objects
Model Objects
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -