Thursday, August 21, 2014

EJ-2 Consider a Builder When Faced with Many Constructor Parameters

Ref: Effective Java by Joshua Bloch

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only required parameters, another with a single optional parameters, a third with two optional parameters, and so on...

Telescoping constructor pattern works, but it is hard to write client code when there are many parameters, harder still to read it.

An alternative way is to use JavaBeans patterns, creating instance with a parameterless constructor than calling setter method of each required parameters.  Unfortunately, the JavaBeans patterns has a serious disadvantages of its own, because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction.

Better to use Builder Pattern, client calls setter-like methods on the builder object to set each optional parameter of interest and then calls parameterless build method to generate the object which is immutable.

In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans. 


No comments: