I was thinking about code structure, and thinking about setters. These used to be void methods, so why don't use some possible return value, to enable some new code structure?
My idea was to change all the properties setters from void to an instance reference, so we can do setters sequentially, or something else. Here is an example:
public class MyClass {
private int foo;
private String bar;
public MyClass setFoo(int foo) {
this.foo = foo;
return this;
}
public MyClass setBar(String bar) {
this.bar = bar;
return this;
}
}
Then in some other place in the code we could do:
...
MyClass myInstance = new MyClass();
myInstance.setFoo(auxFoo).setBar(auxBar);
...
This allow to set all of class properties in a single line, useful in transformation methods.
Or even:
...
return myInstance.setFoo(auxFoo);
This one was my goal, to be able for example to set an error property, while returning it. This can simplify a catch block, for instance.
EDIT: After some answers I need to add:
- The question is just about setters (not about doing this in all methods), and not restricted to chaining, but to other usages like the
return
example. - Could the change from void to something else create any problem? JavaBeans Introspection, for instance.
- Can you see any more advantage or disadvantage of doing this?
I was hoping to see some discussion.