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?
What are the benefits of doing this instead of setting these values in the constructor?
1) Overloading
You can manage the number of value you want to set easily, if you have a lot of parameter to set, but some are optionnal, you don't have to create specific constructor or passing null
value.
new Person("name", 19);
new Person("name", 19, address);
new Person("name", 19, phone);
(those are bad example ;) )
In you case, you just have to call the method you need (same with setters).
2) Identitication
Also, having a lot of parameters in a method/constructor tend to be difficult to read, to identify each parameter context
new Person("frank", "John", "Emma");
person.withName("frank").withFather("john").withMother("Emma");
Passing parameter to a method/constructor is nameless, you have to check the signature to understand what you are passing. With that notation, you have a more verbose and readable code. (again, same with setters).
3) Chainable setter The same would be done with setters but without the chainable feature you have here.
person.setName("name");
person.setAge(19);
person.withName("name").withAge(19);
Other than the readability, I don't think there is really some improvement, the chain need the method to return the instance itself, that give a redondant code in the class itself (return this;
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With