Spring Builders

Raphael De Lio
Raphael De Lio

Posted on

A QA colleague asked me the difference between Lombok's @Builder and @With annotations today

Twitter | LinkedIn | YouTube

Today my team had a shortage of devs (illness, holidays), so we asked our QA colleague to help us and approve a PR so that we could've it merged in time. This PR was pretty simple, we were replacing handmade "with" methods in Java Records with Lombok's @With's annotation.

"How does @With compare to @Builder? We only used @Builder so far."

He asked.

This was my answer:

Basically, when creating obejcts with multiple fields its better to use a builder then to use its constructor.

Constructor:

Person(18, "Raphael", "Santos", "Santos", "Software Developer");
Enter fullscreen mode Exit fullscreen mode

Builder:

Person.setAge(18).setName("Raphael").setCity("Santos").setLastName("Santos").setJob("Software Developer").build()
Enter fullscreen mode Exit fullscreen mode

In the second one, you can see how easier it is to identify what is being populated in the person object. In the first one you could even confuse the surname with the city, which makes it harder to maintain.

Besides that, we are working with Java Records. Those are immutable objects. Once they are created, they cannot be modified.

var person1 = Person.setAge(18).setName("Raphael").setCity("Santos").setLastName("Santos").setJob("Software Developer").build()
Enter fullscreen mode Exit fullscreen mode

If the age has later changed to 19, I cannot modify the original object. I have to create a whole new object copying the properties from the first one:

var person2 = Person.setAge(19).setName(person1.getName()).setCity(person1.getCity()).setLastName(person1.getLastName()).setJob(person1.getJob()).build();
Enter fullscreen mode Exit fullscreen mode

Boring, right?

And thats when @With methods come into place:

var person2 = person1.withAge(19);
Enter fullscreen mode Exit fullscreen mode

All the other properties will be automatically copied. Only the age will have been changed in this case. 😃

Lombok's @With annotation will take care of creating all those "with" methods for us. While the @Builder annotation will take care of applying the Builder pattern to our classes.

How do you rate my explanation to him?

Top comments (0)