Wednesday, 30 March 2011

Comparison of POJB Construction Patterns

There are a number of ways that you can create a Plain Old Java Bean each with their own quirks, benefits and problems, so which is best? The most useful? The safest? The table below compares several POJB construction techniques highlighting the benefits and problems of each one. Just in case you’re wondering, my favourite happens to be the ‘Builder Pattern’ as described in Effective Java by Joshua Bloch, second edition...


PatternDescriptionComments
Standard Java BeanStandard bean creation using setXXX() and getXXX() methods.Objects created are not thread safe and hence prone to error.

Popular pattern, widely used.

Required by various frameworks such as Ibatis.
Telescoping ConstructorsA bean with more than one constructor, each constructor taking a different number of arguments.Messy: leads to lots of confusing constructors that can be difficult to use.

Beans created are immutable and hence thread-safe.
Static factory methods.Uses an immutable bean constructor with static factory methods whose name is usually MyClass.getInstance(…) or MyClass.valueOf(…) with a private bean constructor.Good because the factory methods can have meaningful names (unlike constructors).

Hides object construction and allows object caching if required.

Can return a subtype of the object being built.


You may eventually have a number of factory methods for different situations which may be confusing.
Builder PatternA POJB with a nested builder class used to create and return an instance of the bean you wish to build.Very, very flexible. Allows you to create objects with any number of arguments passed to the constructor.

Hides object construction and allows object caching if required.

Can return a subtype of the object being built.


Least invasive construction method. Add a new attribute to your bean and you don’t have to change lots of code at the points where your object is used.
Requires the most code to be written.

No comments: