<p>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 <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="noreferrer">Builder pattern</a> in <em>Effective Java</em> that is kinda the same).</p>
<p>Basically, all setter methods return the object itself so then you can use code like this:</p>
<pre><code>myClass
    .setInt(1)
    .setString(&quot;test&quot;)
    .setBoolean(true);
</code></pre>
<p>Setters simply return this in the end:</p>
<pre><code>public MyClass setInt(int anInt) {
    // [snip]
    return this;
}
</code></pre>
<p>What is your opinion? What are the pros and cons? Does this have any impact on performance?</p>
<p>Also referred to as the <a href="http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-parameter-idiom.html" rel="noreferrer">named parameter idiom</a> in c++.</p>

[{'answer_id': 31589, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 2, 'selected': False, 'text': "<p>I wouldn't do it myself, because to me it muddies what a particular method does, and the method-chaining is of limited use to me over doing it longhand. It isn't going to send me into a quivering ball of rage and psychosis, though, which is always a good thing. :')</p>\n\n<p>I wouldn't be concerned about performance; just ask Knuth.</p>\n"}, {'answer_id': 31604, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 3, 'selected': False, 'text': '<p>This is called a <a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">Fluent Interface</a>, for reference.</p>\n\n<p>Personally, I think it\'s a pretty neat idea, but a matter of taste really. I think <a href="http://en.wikipedia.org/wiki/Jquery" rel="noreferrer">jQuery</a> works this way.</p>\n'}, {'answer_id': 31606, 'author': 'martinatime', 'author_id': 1353, 'author_profile': 'https://Stackoverflow.com/users/1353', 'pm_score': -1, 'selected': False, 'text': '<p>I agree with @Bernard that method chaining like this muddles the purpose of the setters. Instead I would suggest that if you are always creating chains of setters like this that you create a custom Constructor for your class so instead of</p>\n\n<pre><code>    MyClass\n    .setInt(1)\n    .setString("test")\n    .setBoolean(true)\n  ;\n</code></pre>\n\n<p>You do</p>\n\n<pre><code>new MyClass(1,"test",true);\n</code></pre>\n\n<p>This makes it more readable and you can use this to make your class immutable if you chose to.</p>\n'}, {'answer_id': 31614, 'author': 'mmattax', 'author_id': 1638, 'author_profile': 'https://Stackoverflow.com/users/1638', 'pm_score': 0, 'selected': False, 'text': '<p>This idea is seen a lot in c++, it allows operations to be cascaded...</p>\n\n<p>for example</p>\n\n<pre>\n\nstd::cout &lt;&lt; "this" &lt;&lt; "is" &lt;&lt; "cascading" \n</pre>\n\n<p>is where the stream method &lt;&lt; returns an instance of itself (*this).</p>\n\n<p>see this: <a href="http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm" rel="nofollow noreferrer">http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm</a></p>\n'}, {'answer_id': 31621, 'author': 'Cagatay', 'author_id': 3071, 'author_profile': 'https://Stackoverflow.com/users/3071', 'pm_score': 1, 'selected': False, 'text': '<p>I find this to be in poor style when used in setters. Immutable classes are usually a better fit for chaining, such as:</p>\n\n<pre><code>aWithB = myObject.withA(someA).withB(someB);\n</code></pre>\n\n<p>where <code>myObject</code> is of this class:</p>\n\n<pre><code>class MyClass {\n    withA(TypeA a) {\n         this.a.equals(a) ? this : new MyClass(this, a);\n    }\n\n    private MyClass(MyClass copy, TypeA a) {\n        this(copy);\n        this.a = a;\n    }\n}\n</code></pre>\n\n<p>The builder pattern is also useful, since it allows the final object to be immutable while preventing the intermediate instances you would normally have to create when using this technique.</p>\n'}, {'answer_id': 31625, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 0, 'selected': False, 'text': "<p>I use to be a fan of the Java (and worse C#) practice of making getters and setters (get set properties) throughout an object.  This use to be what I considered object oriented, but really this leads us just to exposing the guts and implementation of the object and not really taking advantage of encapsulation.  There are times you can't get away from this (OR/M comes to mind), but in general the object should be set up and then perform its function.  My dream objects tend to have one or two constructors, and maybe a half dozen functions that do work.</p>\n\n<p>The reason for this is that once I started developing API's there is a real need to keep things simple.  You really only want to add as much complexity as is required to get the job done, and getters and setters, while simple in themselves, add complexity in heaps when added in mass.  What happens when I load setters i na different order?  Anythign different? Are you sure?</p>\n"}, {'answer_id': 31639, 'author': 'pek', 'author_id': 2644, 'author_profile': 'https://Stackoverflow.com/users/2644', 'pm_score': 0, 'selected': False, 'text': '<p>@Dan again, for more complex situations (immutability comes in mind) the Builder Pattern is a great solution.</p>\n\n<p>Also, I agree with you mostly in getters. I believe what you are saying is to mostly follow the "<a href="http://www.pragprog.com/articles/tell-dont-ask" rel="nofollow noreferrer">Tell don\'t ask</a>" paradigm and I greatly agree. But that is oriented mostly at getters.</p>\n\n<p>Lastly, all of the above are for classes that have a great deal of attributes. I don\'t see a reason for any if you only have less than, say, 7.</p>\n'}, {'answer_id': 37005, 'author': 'Bartosz Bierkowski', 'author_id': 3666, 'author_profile': 'https://Stackoverflow.com/users/3666', 'pm_score': 5, 'selected': True, 'text': '<p>@pek<br/>\nChained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return <strong>this</strong>. If you\'re interested in this topic, there is a bunch of links and a simple example on <a href="http://tech.puredanger.com/java7#chained" rel="noreferrer">Alex Miller\'s Java 7 page</a>.</p>\n'}, {'answer_id': 39948, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 0, 'selected': False, 'text': '<p>I ended up doing this a lot when working with the Apache POI excel library; I ended up writing helper methods that chained so I could apply formatting, data types, internal cell data, formulas, and cell positioning.</p>\n\n<p>For stuff with lots of little tiny flyweight elements that need to have finicky little tweaks applied it works pretty well.</p>\n'}, {'answer_id': 46858, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 1, 'selected': False, 'text': '<p>It makes sense for builders, where all you are going to do is set a load of stuff, create the real object and throw the builder away. For builders, you might as well get rid of the "set" part of the method name. Similarly, immutable types don\'t really need the "get".</p>\n\n<pre><code>Something thing = new SomethingBuilder()\n    .aProperty(wotsit)\n    .anotherProperty(somethingElse)\n    .create();\n</code></pre>\n\n<p>A useful trick (if you don\'t mind a ~2K runtime overhead per class) is to use the double brace idiom:</p>\n\n<pre><code>JFrame frame = new JFrame("My frame") {{\n    setDefaultCloseOperation(DISPOSE_ON_CLOSE);\n    setLocation(frameTopLeft);\n    add(createContents());\n    pack();\n    setVisible(true);\n}};\n</code></pre>\n'}, {'answer_id': 3741052, 'author': 'Sanjay Mishra', 'author_id': 451308, 'author_profile': 'https://Stackoverflow.com/users/451308', 'pm_score': 0, 'selected': False, 'text': '<p>How To Use</p>\n\n<pre><code>/**\n *\n * @author sanjay\n */\npublic class NewClass {\nprivate int left ;\nprivate int top;\npublic void set(int x,int y)\n    {\n    left=x;\n    top=y;\n}\npublic NewClass UP(int x)\n    {\n    top+=x;\n    return this;\n}\npublic NewClass DOWN(int x)\n    {\n    top-=x;\n    return this;\n}\npublic NewClass RIGHT(int x)\n    {\n    left+=x;\n    return this;\n}\npublic NewClass LEFT(int x)\n    {\n    left-=x;\n    return this;\n}\npublic void Display()\n    {\n    System.out.println("TOP:"+top);\n    System.out.println("\\nLEFT\\n:"+left);\n}\n}\npublic static void main(String[] args) {\n    // TODO code application logic here\n    NewClass test = new NewClass();\n    test.set(0,0);\n    test.Display();\n    test.UP(20).UP(45).DOWN(12).RIGHT(32).LEFT(20);\n     test.Display();\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/31584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2644/']