Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's wrong with returning this?
    primarykey
    data
    text
    <p>At the company I work for there's a document describing good practices that we should adhere to in Java. One of them is to avoid methods that return <code>this</code>, like for example in:</p> <pre><code>class Properties { public Properties add(String k, String v) { //store (k,v) somewhere return this; } } </code></pre> <p>I would have such a class so that I'm able to write:</p> <pre><code> properties.add("name", "john").add("role","swd"). ... </code></pre> <p>I've seen such idiom many times, like in <code>StringBuilder</code> and don't find anything wrong with it.</p> <p>Their argumentation is :</p> <blockquote> <p>... can be the source of synchronization problems or failed expectations about the states of target objects. </p> </blockquote> <p>I can't think of a situation where this could be true, can any of you give me an example?</p> <p><strong>EDIT</strong> The document doesn't specify anything about mutability, so I don't see the diference between chaining the calls and doing: </p> <pre><code>properties.add("name", "john"); properties.add("role", "swd"); </code></pre> <p>I'll try to get in touch with the originators, but I wanted to do it with my guns loaded, thats' why I posted the question.</p> <p><strong>SOLVED</strong>: I got to talk with one of the authors, his original intention was apparently to avoid releasing objects that are not yet ready, like in a Builder pattern, and explained that if a context switch happens between calls, the object could be in an invalid state. I argued that this had nothing to do with returning <code>this</code> since you could make the same mistake buy calling the methods one by one and had more to do with synchronizing the building process properly. He admitted the document could be more explicit and will revise it soon. Victory is mine/ours!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload