Builder Pattern

But why?
Imagine the headache constructing complex objects from constructor that has more than 5 arguments.
Then you need to remember what is what & you explicitly need to send null
for any property that you do not want to set.
Take for example below snippet:
Builder Pattern
Builder Pattern addresses this problem statement by following a step-by-step approach. Essentially it creates the entire object from small steps.
This comes handy when we have a complex object & a constructor does not help with being informative.
How its done?
The implementation is simple. We just create a separate class that provides steps (methods) to set individual properties with ease. Finally it will return the desired object.
- Create your entity as normal but for the constructor make it private & let it accept a single argument as builder
- Create a
static
inner class as builder - The builder is required to have same properties as your entity
- The builder then also provide methods for setting each property & return itself
- Below is a snippet for builder
- Below snippet shows how to construct objects using this builder
- The way we now initialize objects is very clean & readable.
Caveats?
Yes like everything else, we need to maintain the builder with same properties which is cumbersome.