Say you have a class called Person, and a Person has attributes such as name, id, age, etc. Instead of setting these values in the constructor, one does
new Person().withName("Lorem").withId("1234").withAge(29)
Where a with method is a call to a set method, and returns the object, e.g.,
public Person withAge(int age) {
this.setAge(age);
return this;
}
On a current project, I see a lot of code like this, often with 5-10 chained calls to different with methods. What are the benefits of doing this instead of setting these values in the constructor?
Aucun commentaire:
Enregistrer un commentaire