Design: Java and returning self-reference in setter methods

Question :

Design: Java and returning self-reference in setter methods,

Answer :

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 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?

Read More  Code crash in MS Visual Studio 2005 in RELEASE configuration

Also referred to as the  in c++.

,

@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

That’s the answer Design: Java and returning self-reference in setter methods, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Read More  Planning and Building a mobile enabled site for your main site

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you