For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same).
Basically, all setter methods return the object itself so then you can use code like this:
myClass
.setInt(1)
.setString("test")
.setBoolean(true);
Setters simply return this in the end:
public MyClass setInt(int anInt) {
// [snip]
return this;
}
What is your opinion? What are the pros and cons? Does this have any impact on performance?
Also referred to as the named parameter idiom in c++.
well, generally you don't return anything from a setter anyway, by convention. Maybe not to start with, but a setter doesn't necessarily keep its original purpose.
Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
A self-referential class contains an instance variable that refers to another object of the same class type. For example, the declaration.
return this; When you return "this" from a method the current object will be returned.
@pek
Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.
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