Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design: Java and returning self-reference in setter methods [closed]

Tags:

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++.

like image 541
pek Avatar asked Aug 28 '08 03:08

pek


People also ask

Do setters have a return type java?

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.

Should a setter return value?

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.

What is self reference in Java?

A self-referential class contains an instance variable that refers to another object of the same class type. For example, the declaration.

What is return this in Java?

return this; When you return "this" from a method the current object will be returned.


1 Answers

@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.

like image 65
Bartosz Bierkowski Avatar answered Sep 27 '22 19:09

Bartosz Bierkowski