lombok @Builder vs constructor

Vitalii :

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?

Shadov :

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?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465069&siteId=1