Saturday, December 30, 2017

Builder pattern using Lombok

The idea of builder pattern is simple. It provides users with a better interface to construct a complex object - in other words better readability at the site an object is created. Another important aspect which is sometimes missed is that the patten helps in achieving immutability unlike having getter/setter methods with in the class.

When it comes to implementing the pattern, I am a bit biased towards the way Effective Java advocates. It preserves the class’s contract by specifying mandatory parameters through constructor.

Certainly when creating libraries or APIs its better to start off with builders if we want to create immutable objects and there are more than ‘x’ number of optional parameters. I generally consider 4 as a guideline for ‘x’.

Now all this can be easily achieved using lombok. @Builder annotation auto-generates the inner builder classes. What I don’t like is the lack of support of compile time check for mandatory attributes of a class. At the time of this writing there seems to be some thought process going on within lombok’s dev community to support the same as per this link.

Until then the tradeoff to use lombok is the ease to create builders versus the compile-time check for mandatory attributes. The consistency of the object's state can be managed through run time validations and hence the compile-time check is not a show stopper.

Overall I vote a Yes to use lombok's @Builder and am hoping that the support of compile time validation is available sooner than later.