What about this approach?
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true, fluent = true)
public class Person {
private final String name; // 'final' prevents lombok from creating a setter method
private String surname;
public Person(String name) {
this.name = name; // mandatory
this.surname = null; // optional, with default value of 'null'
}
public static void main(String[] args) {
Person gabi = new Person("Gabriela");
Person smith = new Person("John").surname("Smith");
System.out.println(gabi);
System.out.println(smith);
}
}
Executing main()
will print:
Person(name=Gabriela, surname=null)
Person(name=John, surname=Smith)
The combination of
@Data
@Accessors(chain = true, fluent = true)
Makes lombok create setters that return this
instead of void, and the getters and setters will be named as the property names, without 'get' and 'set' prefix.
There will be a setter for surname()
, but because name
is final
, there won't be a setter for name
.
I guess this implemenation correctly accomodates the builder pattern when there are mandatory and optional fields.