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?
@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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With