Sep 19, 2013

When to use a builder design pattern? real life tips

Interview questions relating to design patterns are very popular in job interviews. Even if this topic is not covered in rare occassions, you can bring it up yourself to open-ended questions to impress your interviewers.Q. What are the key difference(s) between a factory and a builder design patterns?A. The builder design patternbuilds an object over several steps. It holds the needed state for the target item at each intermediate step. The StringBuilder is a good example that goes through to produce a final string. Here is a real world example that shows how builders are used instead of constructors to create Immutable objects. Creating immutable objects where applicable is a development best practice.

To construct a complex object. For example, to construct XML DOM objects and any other hierachichal objects. You have to create plenty of nodes and attributes to get your final object.

Builder pattern makes your code more readable as explained in the article "Using Builders instead of Constructors to create Immutable objects". The article explains how you can create immutable objects in Java by using the builder design pattern as opposed to using multiple constructors, which is known as the "telescoping constructor anti pattern".Firstly, let's see what is not so elegant about using a constructor as shown below with a CashBalance object that takes 3 BigDecimal arguments. Then we will see how a builder class will make your code more intuitive.