Note that there are some explanatory texts on larger screens.

plurals
  1. POChained invocation in Java 7?
    text
    copied!<p>I was just reading a <a href="http://puredanger.com/techfiles/090204/Java7Preview.pdf" rel="nofollow noreferrer">Java 7 preview presentation (pdf)</a> and there was a slide on <em>Chained Invocation</em>. Here is the example used in the slide:</p> <pre><code>// Construction with setters DrinkBuilder margarita = new DrinkBuilder(); margarita.add("tequila"); margarita.add("orange liqueur"); margarita.add("lime juice"); margarita.withRocks(); margarita.withSalt(); Drink drink = margarita.drink(); // Construction with chained invocation Drink margarita = new DrinkBuilder() .add("tequila") .add("orange liqueur") .add("lime juice") .withRocks() .withSalt() .drink(); </code></pre> <p>And I have mixed feelings about this. One shouldn't chain too many method invocations into one statement. On the other hand, writing <code>margarita.this()</code> and <code>margarita.that()</code> isn't too convenient either.</p> <p>Now, I am coming to Java from Delphi world. And in Delphi there is the <a href="http://www.delphibasics.co.uk/RTL.asp?Name=With" rel="nofollow noreferrer"><code>with</code></a> language construct. This is cherished by a few and loathed by many (or is it the other way around?). I find <code>with</code> to be more elegant than the idea of chained invocation (which I believe works on the basis of <code>void</code> method returning reference to object on which it has been invoked - and this is the part I don't like, as <code>void</code> should return <em>nothing</em>).</p> <p>I would appreciate the <code>with</code> language feature being adopted by Java, so the example code could be written like so:</p> <pre><code>Drink margarita = null; with (new DrinkBuilder()) { add("tequila"); add("orange liqueur"); add("lime juice"); withRocks(); withSalt(); margarita = drink(); } </code></pre> <p>Am I the only one who would prefer this solution to the chained invocation? Anyone else feels that <code>with</code> could be a useful extension to Java language? (Reminds me of someone's question about the need of "Java++"...)</p>
 

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