Saturday 22 November 2008

Item 2: Consider a builder when faced with many constructor parameter

tem 2 describes the Builder Pattern and when it should be used.

The item gives an example of a class that has a number of optional properties that should be initialised via a constructor and explains how they can be initialized using the telescoping constructor pattern or the JavaBean pattern. It concludes that "the telescoping constructor pattern works, but it is hard to write client code where there are many parameters, and harder still to read it" and that "the JavaBean pattern precludes the possibility of making a class immutable." His argument in both cases is convincing.

As a solution, the item suggests a variation on the builder pattern. Basically, the class with the optional properties has an inner class that can be used to intialise the properties on construction. The resulting initialisation syntax looks like this:
NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();
The item points out that "the builder pattern stimulates named optional parameters" and that the pattern does not really become useful until you have at least four optional properties and if needed should be used as soon as possible as refactoring to the pattern can be problematic.

The item summarises the build pattern as "a good choice when designing classes whose constructors or static factories would have more than a handful of parameters."

I wish this had occurred to me before. I could have used it in so many places. Again, it's not Java specific.

No comments: