Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lombok @Builder vs constructor

Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call?

MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")

Is it just a question of better visibility?

like image 724
Vitalii Avatar asked Nov 17 '17 15:11

Vitalii


People also ask

What does @builder in Lombok do?

@Builder(access = AccessLevel. PACKAGE) is legal (and will generate the builder class, the builder method, etc with the indicated access level) starting with lombok v1.

What is difference between @builder and @SuperBuilder?

The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.

Is builder better than constructor?

Building an object in the builder class allows to encapsulate logic related to building an object in one place. Also you can deal more easily with dependencies required to for object construction than using regular constructor.

Does Lombok builder create constructor?

Then when we put the @Builder annotation on the constructor, Lombok creates a builder class containing only the constructor parameters. We're adding two more fields here: section and school. Then we're creating a constructor with these fields and annotating the constructor with @Builder.


1 Answers

This is not a lombok specific feature, this is called a builder pattern.

Imagine you have a class with 20 parameters, and 10 of them are optional. You could somehow make tons of constructors taking care of this logic, or make a constructor with all those arguments and pass nulls in some places. Isn't builder pattern simply easier?

like image 130
Shadov Avatar answered Sep 28 '22 06:09

Shadov