简体   繁体   中英

lombok @Builder vs constructor

I'm quite new to java. 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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM