Vitalii
Vitalii

Reputation: 11071

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?

Upvotes: 14

Views: 12626

Answers (2)

slim
slim

Reputation: 41223

Consider:

Order order = new Order("Alan", "Smith", 2, 6, "Susan", "Smith");

What do the parameters mean? We have to look at the constructor spec to find out.

Now with a builder:

Order order = Order.builder()
    .originatorFirstName("Alan")
    .originatorLastName("Smith")
    .lineItemNumber(2)
    .quantity(6)
    .recipientFirstName("Susan")
    .recipientLastName("Smith")
    .build();

It's more wordy, but it's very clear to read, and with IDE assistance it's easy to write too. The builders themselves are a bit of a chore to write, but code-generation tools like Lombok help with that.

Some people argue that if your code needs builders to be readable, that's exposing other smells. You're using too many basic types; you're putting too many fields in one class. For example, consider:

Order order = new Order(
     new Originator("Alan", "Smith"),
     new ItemSet(new Item(2), 6),
     new Recipient("Susan", "Smith"));

... which is self-explanatory without using a builder, because we are using more classes with single-responsibilities and fewer fields.

Upvotes: 20

Shadov
Shadov

Reputation: 5592

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?

Upvotes: 14

Related Questions