Sitemap
சுட சுட Code

Stay afloat with technology wave

Oh !! Stop using @Builder

--

Press enter or click to view image in full size

The days of writing getters and setters, or generating them using an IDE, are gone. The Lombok plugin has improved developer productivity by eliminating the boilerplate code that we usually write day-in and day-out.

I’ve seen most developers use Lombok annotations that look similar to this:

Usage of Builder :(

I've seen this snippet in one of the application services at a large retail-tech company, where even the tech lead reviewed the code which looked like this

Snippet almost looked similar to this that was part of the code review

suggested to re-write using @Builder that would look like this

Post Review

But Do we need a builder? Nope !! We don't

Anit-patterns that I see here,

  1. Builders (Builder Pattern) should not have @Setters. Builders are immutable objects and should not be modified once instantiated. Builders are best suited for objects that live throughout the application lifecycle, but that does not mean you cannot use them for short-lived objects.
  2. Not all parameters can be optional in builders. Some should be mandatory, otherwise, the constructor should create default values of the same.

Builders are used to construct different flavors of the same object (often compared to the Abstract Factory pattern), which means that the type of every member variable in the class should be an abstract type, not a concrete one. This allows you to build different flavors of the object by passing concrete objects when the objects get instantiated. Other times, one or more member variables are treated as optional.

Lombok's @Builder does not generate a perfect builder where it can have mandatory parameters. We can write one instead.

A person with Builder Pattern

I think most developers use @Builder so that they can have a fluent way of instantiating and populating its member variables on the go. Sorry, folks! @Builder isn’t for you. Use @Accessor instead :)

APIResponse with @Accessor (experimental)

When @Accessor is used with the argument chain as true, Lombok generates setters that will return this (instance of the object itself), which allows one to write a fluent construction of the object. A decompiled version of the Lombok class looks like this:

Setters return `this`

And can be used like this,

Fluent usage with setters

If you find this article to be useful, please consider upvoting it. I guess it motivates me to improve my writing

Happy coding :)

Feel free to connect with me on my professional network here

--

--

Vivekanandan Sakthivelu
Vivekanandan Sakthivelu

Written by Vivekanandan Sakthivelu

Conscious-being stuck in space-time continuum, who find solace in Kahlil Gibran writings. Sometimes I code,write;othertimes I enjoy melodrama of my own thoughts

Responses (18)