lombok @Builder vs constructor

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?


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.