Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes simulation of closures in Java make sense?
    primarykey
    data
    text
    <p>Languages that have closures, such as Ruby, enable elegant constructs to transform lists. Suppose we have a class</p> <pre><code>class QueryTerm { String value; public String getValue() {...} } </code></pre> <p>and a list of terms <code>List&lt;QueryTerm&gt; terms</code>, that we want to transform into its list of values <code>List&lt;String&gt; values</code>.</p> <p>In Ruby we could write something like:</p> <pre><code>values1 = terms.collect do |term| term.getValue() end </code></pre> <p>Java forces us to <strong>construct the result list</strong> and <strong>iterate through the terms collection</strong> ourselves (at least there is no iterator or index position involved since foreach was introduced):</p> <pre><code>Collection&lt;String&gt; values2 = new HashSet&lt;String&gt;(); for (QueryTerm term : terms) { values2.add(term.getValue()); } </code></pre> <p><a href="http://commons.apache.org/collections/" rel="nofollow noreferrer">Apache Commons</a> and <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Collections2.html" rel="nofollow noreferrer">Google Collections2</a> try to emulate closures in Java by using anonymous classes:</p> <pre><code>Collection&lt;String&gt; values3 = Collections2.transform(terms, new Function&lt;QueryTerm, String&gt;() { @Override public String apply(QueryTerm term) { return term.getValue(); } }); </code></pre> <p>The weird thing is, that this version has more lines of code and more characters than the original version! I would assume it is harder to understand for this reason. Therefore I dismissed the idea back when I saw it in Apache Commons. However, having seen it introduced in Google Collections recently I am starting to wonder if I am missing something.</p> <p><strong>Therefore my question: What is your opinion of the constructs above? Do you consider the <code>Collections2.transform()</code> version more readable/understandable than the default one? Am I missing something completely?</strong></p> <p>Best regards, Johannes</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.
    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