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:
return
example.I was hoping to see some discussion.
It's a common technique, known as Method Chaining. Hibernate uses it in its Criteria classes, and is present in other popular frameworks, such as Wicket.
Generally, you've got to be careful and apply it in those void
methods that you're sure that will never need to return anything. And you shouldn't be using it in your Java Beans, as it has been already discussed in this question: Does Java bean's setter permit return this?.
See this related SO question for some tips and drawbacks that may be useful while using this pattern.
This is quite common practice and definitely a pattern - not an anti-pattern. It is more commonly referred to as :
http://en.wikipedia.org/wiki/Fluent_interface
and
http://en.wikipedia.org/wiki/Method_chaining
Some excellent libraries make use of it : jQuery and joda-time.
You can also specify when the chain ends by using an end method that does not return anything, or does something else entirely - in the case of an inner static builder it calls a constructor.
For what its worth I really like it.
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