<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>stuart_halloway's blog</title>
  <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/blog/186"/>
  <link rel="self" type="application/atom+xml" href="http://www.javaworld.com/community/blog/186/atom/feed"/>
  <id>http://www.javaworld.com/community/blog/186/atom/feed</id>
  <updated>2008-08-12T17:50:47-04:00</updated>
  <entry>
    <title>Java.next #4: Immutability</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/1356" />
    <id>http://www.javaworld.com/community/node/1356</id>
    <published>2008-09-17T20:02:08-04:00</published>
    <updated>2008-09-17T20:04:55-04:00</updated>
    <author>
      <name>stuart_halloway</name>
    </author>
    <category term="Clojure" />
    <category term="concurrency" />
    <category term="Dynamic Languages" />
    <category term="groovy" />
    <category term="immutability" />
    <category term="Java.next" />
    <category term="jruby" />
    <category term="scala" />
    <category term="Stuart Hallowy" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>This is Part Four of a series of articles on Java.next. In Part Four, I will begin to explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) deal with concurrency. Concurrency is a big topic, so I will subdivide it, narrowing my focus in this part to how the Java.next languages support immutability.</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>This is Part Four of a series of articles on Java.next. In Part Four, I will begin to explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) deal with concurrency. Concurrency is a big topic, so I will subdivide it, narrowing my focus in this part to how the Java.next languages support immutability.</p>

<h3>Why concurrency?</h3>

<p>Over the last decade, most programmers have written code with little concern for concurrency. Often this has caused problems later, when programs needed to be used in a more concurrent setting. This is only going to get worse: in the future, everything is concurrent.</p>

<p>Why don't programmers do a better job with concurrency? Because it is <em>hard</em>. Read the excellent <a href="http://jcip.net/">Java Concurrency in Practice</a> (JCIP), and you will come away impressed with all the clever work that has gone into making Java a good environment for writing concurrent applications. But may also come away thinking "Who is smart enough to get this kind of code right in production?" </p>

<p>Not many people can, and the experts agree that we need an entirely different paradigm for writing concurrent applications. It may even be the case that supporting concurrency is the number one priority for Java.next.</p>

<h3>Why immutability?</h3>

<p>One of the most difficult things about writing concurrent programs is deciding how to protect mutable shared state. Java provides a locking primitive, <code>synchronized</code>, but locking primitives are difficult to use. You have to worry about</p>

<ul>
<li>data corruption (if you lock too little)</li>
<li>deadlock (if you lock too much)</li>

<li>performance degradation (even if you get it right) </li>
</ul>

<p>To make matters worse, it is generally impractical to write automated tests that explore the various possible interleavings of events.</p>

<p>Immutability solves all these problems of locking, by removing the need for ever locking at all. Immutable state can always be shared safely. Nobody can ever see a corrupt value <em>by definition</em>, as values never change.</p>

<p>All of the Java.next languages support immutability to some degree, as I will show below.</p>

<h3>Immutability in JRuby</h3>

<p>JCIP uses a <code>ThreeStooges</code> class as an extremely simple example for creating immutable objects in Java. Continuing the theme of that example, here is JRuby's immutable stooges:</p>

<pre><div class="codeblock"><code>require &#039;set&#039;<br /><br />class ThreeStooges<br />&nbsp; def initialize(*names)<br />&nbsp;&nbsp;&nbsp; @stooges = Set.new(names)<br />&nbsp;&nbsp;&nbsp; @stooges.freeze<br />&nbsp;&nbsp;&nbsp; self.freeze<br />&nbsp; end<br />&nbsp; def stooge?(name)<br />&nbsp;&nbsp;&nbsp; @stooges.member?(name)<br />&nbsp; end<br />end</code></div></pre>

<p>In Ruby, you can set immutability on a per-instance basis, as opposed to a per-class basis. A particular object can become immutable by calling <code>freeze</code>. If the internal components of that object are not primitive, they will need to <code>freeze</code> as well. So, in the constructor above, I <code>freeze</code> the two things at risk of changing: <code>stooges</code> and <code>self</code>.</p>

<p>While immutability is possible in Ruby, be warned. Heavy use of <code>freeze</code> to enable safe concurrency is <em>far</em> from idiomatic.</p>

<h3>Immutability in Groovy</h3>

<p>In Groovy, the <code>ThreeStooges</code> class looks and works like Java, but prettier:</p>

<pre><div class="codeblock"><code>class ThreeStooges { <br />&nbsp; private final Set&amp;lt;String&amp;gt; stooges;<br />&nbsp; ThreeStooges(String... args) {<br />&nbsp;&nbsp;&nbsp; stooges = args as HashSet&amp;lt;String&amp;gt;;<br />&nbsp; }<br />&nbsp; boolean isStooge(String name) {<br />&nbsp;&nbsp;&nbsp; return stooges.contains(name); <br />&nbsp; }<br />}</code></div></pre>

<p>The important details here are that the internal <code>stooges</code> collection is </p>

<ul>
<li><code>final</code> (cannot be changed after the object is created)</li>

<li><code>private</code> (cannot be accessed outside the object itself)</li>
</ul>

<p>I could also wrap <code>stooges</code> with <code>unmodifiableSet</code>, but since the <code>ThreeStooges</code> class already wraps <code>stooges</code> without exposing a modifying method, the second wrap is redundant.</p>

<h3>Immutability in Scala</h3>

<p>In JRuby and Groovy, immutability is possible. In Scala, immutability is <em>preferred</em>. The default collection classes are immutable, so <code>ThreeStooges</code> is just</p>

<pre><div class="codeblock"><code>class ThreeStooges(names: String*) {<br />&nbsp; private val stooges = Set() ++ names<br />&nbsp; def isStooge(name: String) = stooges(name)<br />}</code></div></pre>

<p>A few observations here:</p>

<ul>
<li>In Scala, fields must be declared <code>val</code> (immutable) or <code>var</code> (changeable). Scala style encourages you to use <code>val</code> where possible.</li>
<li>Scala's <code>Set</code> is immutable.</li>

</ul>

<p>I find that Scala's inline constructor syntax and braces-free method definition syntax make the Scala definition easier to read than the JRuby or Groovy versions. </p>

<h3>Immutability in Clojure</h3>

<p>In Clojure, immutability is the default. In fact, <em>everything</em> is immutable, with only two exceptions:</p>

<ul>
<li>calling down into Java APIs (the Clojure version of assembly language)</li>

<li>a few data structures which are specifically designed to support Software Transactional Memory (more on this in a later post)</li>
</ul>

<p>So, the <code>three-stooges</code> can just be a set:</p>

<pre><div class="codeblock"><code>(defn three-stooges [&amp;amp; names] (set names))<br />(defn is-stooge? [name stooges] (stooges name))</code></div></pre>

<p>A few observations:</p>

<ul>
<li><code>[&amp;amp; names]</code> is Clojure's varargs syntax.</li>
<li>A set can be placed in function position (first item in a list). So <code>(stooges name)</code> can be read as "find <code>name</code> in the set <code>stooges</code>"</li>

</ul>

<h3>Putting immutables to work</h3>

<p>To see how immutables can simplify an implementation, consider the <code>Factorizer</code> servlet example from JCIP. The objectives of this example are to</p>

<ul>
<li>calculate the prime factorization of a number</li>
<li>cache the most recent factorization</li>
<li>use the cached answer where possible, and track the frequency of cache hits</li>

<li>track the total number of factorizations</li>
</ul>

<p>Here is a Java version of the factorizer using synchronized blocks, and stripped down to bare essentials for clarity:</p>

<pre><div class="codeblock"><code>import java.math.BigInteger;<br /><br />public class CachedFactorizer {<br />&nbsp;&nbsp;&nbsp; private BigInteger ;<br />&nbsp;&nbsp;&nbsp; private BigInteger[] lastFactors;<br />&nbsp;&nbsp;&nbsp; private long hits;<br />&nbsp;&nbsp;&nbsp; private long cacheHits;<br /><br />&nbsp;&nbsp;&nbsp; public void factors(BigInteger i) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BigInteger[] factors = null;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; synchronized (this) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ++hits;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (i.equals(lastNumber)) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ++cacheHits;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; factors = lastFactors.clone();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (factors == null) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; factors = factor(i);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; synchronized (this) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; lastNumber = i;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; lastFactors = factors.clone();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return factors;<br />&nbsp;&nbsp;&nbsp; }<br />}</code></div></pre>

<p>In order for the <code>CachedFactorizer</code> to be correct and efficient, you need to think carefully about where the synchronized blocks should go. In the example above, there are two synchronized blocks. The first block checks the cache, and updates the counters. It protects:</p>

<ul>

<li>read and write of <code>hits</code></li>
<li>read and write of <code>cacheHits</code></li>
<li>read of <code>lastFactors</code></li>
</ul>

<p>The second block updates the cache. It protects:</p>

<ul>
<li>write of <code>lastNumber</code></li>

<li>write of <code>lastFactors</code></li>
</ul>

<p>To make sure you understand the approach, ask yourself the following questions:</p>

<ul>
<li>Could the first synchronized block be split into multiple, more granular locks? Would this likely be faster or slower?</li>
<li>What about the second block?</li>
<li>What operations are unprotected by locks? Is this safe?</li>
<li>Would a simple, single-lock approach be correct? Under what circumstances would it perform well?</li>

</ul>

<p>That's a lot to think about. Now, let's consider the same example, but using immutable data structures.</p>

<h3>A Clojure cached-factor</h3>

<p>Here is one Clojure approach to <code>cached-factor</code>:</p>

<pre><div class="codeblock"><code>(def #^AtomicLong hits (AtomicLong. 0))<br />(def #^AtomicReference cache (AtomicReference. {:n nil :factors nil}))<br />(def #^AtomicLong cache-hits (AtomicLong. 0))<br /><br />(defn cached-factor [n]<br /> (.incrementAndGet hits)<br /> (let [cached (.get cache)]<br />&nbsp;&nbsp; (if (= n (cached :n))<br />&nbsp;&nbsp;&nbsp;&nbsp; (do (.incrementAndGet cache-hits)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (cached :factors))<br />&nbsp;&nbsp;&nbsp;&nbsp; (let [factors (factor n)]<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (.set cache {:n n :factors factors})<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; factors))))</code></div></pre>

<p>There are several things to notice here:</p>

<ul>
<li>The <code>hits</code>, <code>cache</code>, and <code>cache-hits</code> take advantage of Java 5's atomic wrapper classes. (The <code>#^ClassName</code> syntax adds type information.)</li>
<li>There are no synchronized blocks anywhere.</li>
<li>Even though there are no synchronized blocks, you still have to think about the semantics of concurrency. The <code>incrementAndGet</code> method is used to update the two hit counters, and the <code>cache</code> is pulled into a local variable to avoid inconsistent reads.</li>

</ul>

<p>The real key to this approach, however, is storing a Clojure map in an <code>AtomicReference</code>. Because Clojure data structures are immutable, they can benefit from an <code>AtomicReference</code> in a way that mutable classes cannot. </p>

<p>The immutable approach looks only a little simpler in this small example. But the benefit of using immutable data <em>increases</em> when you compose objects together. If you wanted to compose the synchronized version with another object,  you would have have to dig back into the internals of both objects, study their locks, and pick a new lock strategy to cover the two objects together. Composing operations with immutable objects is much easier. </p>

<h3>A Scala CachedFactor</h3>

<p>Since Scala's default collections are immutable, a Scala approach can closely parallel the Clojure code above:</p>

<pre><div class="codeblock"><code>class CachedFactorizer {<br />&nbsp; case class Cache(val n: Int, val factors: List[Int])<br />&nbsp; val hits = new AtomicLong()<br />&nbsp; val cache = new AtomicReference[Cache](Cache(2, calculateFactors(2)))<br />&nbsp; val cacheHits = new AtomicLong()<br /><br />&nbsp; def factor(n: Int) = {<br />&nbsp;&nbsp;&nbsp; hits.incrementAndGet<br />&nbsp;&nbsp;&nbsp; val cached = cache.get<br />&nbsp;&nbsp;&nbsp; if (cached.n == n) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cacheHits.incrementAndGet<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cached.factors<br />&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; val factors = calculateFactors(n)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cache.set(Cache(n, factors))<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; factors<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp; }</code></div></pre>

<p>While this is similar to the Clojure approach, the difference is instructive. While the Clojure version stores the cache as a simple Map, the Scala version introduces a strongly-typed <code>Cache</code> class for the cache of values and their factors. The differences here are intended to idiomatic. Either approach could work in either language.</p>

<h3>What about the JRuby and Groovy examples?</h3>

<p>Could you write the example above in Groovy, JRuby, or even Java? Yes, but it would be non-idiomatic, even ugly. I am not going to show the JRuby and Groovy versions here, because those languages do not offer any <em>concurrency-specific</em> advantages over Java. Scala and Clojure, on the other hand, don't just make immutable objects <em>possible</em>. They make them easy and idiomatic.</p>

<p>Languages are designed to support certain priorities, inevitably at the expense of others. By making immutability a preferred option (Scala) or the standard (Clojure), these languages are encouraging a different paradigm for concurrent applications.   </p>

<p><em>Languages are not about what they make possible, but about what they make beautiful</em>. Clojure and Scala aim to make concurrent programs beautiful, and their preference for immutability is but the tip of the iceberg. In the next installment of this series, I will explore how Clojure and Scala enable concurrent programs through actors, agents, and software transactional memory.</p>

<h3>Notes</h3>

<ul>
<li>This article is based on the talk <a href="http://blog.thinkrelevance.com/2008/9/9/java-next-presentation-4-concurrency">Java.next #4: Concurrency </a>. Check the <a href="http://thinkrelevance.com/events">schedule</a> for a talk near you.</li>

<li>Thanks to Greg Vaughn and Glenn Vanderburg for their feedback on a draft of this article.</li>
<li>Thanks to Rich Hickey for suggesting <a href="http://groups.google.com/group/clojure/browse_thread/thread/77d2bdb1066aac1e/10d7ff52e0823815?hl=en&amp;lnk=gst&amp;q=halloway#10d7ff52e0823815">several Clojure versions</a> of the factorizer example.</li>
<li>Feedback on how to improve these examples is most welcome!</li>
<li>This article was originally published at <a href="http://blog.thinkrelevance.com/2008/9/10/java-next-4-immutability">http://blog.thinkrelevance.com</a>.</li>
</ul>    ]]></content>
  </entry>
  <entry>
    <title>Java.next #3: Dispatch</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/1330" />
    <id>http://www.javaworld.com/community/node/1330</id>
    <published>2008-09-09T01:22:13-04:00</published>
    <updated>2008-09-09T01:22:13-04:00</updated>
    <author>
      <name>stuart_halloway</name>
    </author>
    <category term="Clojure" />
    <category term="Dynamic Languages" />
    <category term="groovy" />
    <category term="Java.next" />
    <category term="jruby" />
    <category term="scala" />
    <category term="Stuart Halloway" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>This is Part Three of a series of articles on Java.next. In Part Three, I will explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) support dispatch.</p>

<p>For my purposes here, <em>dispatch</em> is a broad term covering various methods of <em>dynamically choosing behavior</em>: single dispatch, switch/case, pattern matching and multiple dispatch. These concepts are not generally grouped together, but they should be. They are used to solve similar problems, albeit in very different ways.</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>This is Part Three of a series of articles on Java.next. In Part Three, I will explore how the Java.next languages (JRuby, Groovy, Clojure, and Scala) support dispatch.</p>

<p>For my purposes here, <em>dispatch</em> is a broad term covering various methods of <em>dynamically choosing behavior</em>: single dispatch, switch/case, pattern matching and multiple dispatch. These concepts are not generally grouped together, but they should be. They are used to solve similar problems, albeit in very different ways.</p>

<h3>Single dispatch</h3>

<p>Let me start with single dispatch. In Java, methods can be selected based on the type of the object they are invoked on. All the Java.next languages support single dispatch, too:</p>

<pre><div class="codeblock"><code>; clojure<br />(fly vehicle speed)<br /><br />// Java, Groovy, or Scala<br />vehicle.fly(speed)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /><br /># ruby<br />vehicle.fly speed</code></div></pre>

<p>In all of these languages, the actual implementation of <code>fly</code> can vary depending on the run-time type of <code>vehicle</code>. (Clojure also supports multiple dispatch, where the implementation can vary based on the type of <code>speed</code> -- more on that later.)</p>

<h3>Better switching</h3>

<p>Another way to dynamically choose behavior is with a switch statement. Java has a simple switch statement, based on its historical kinship with C and C++. Switch statements have gotten a bad name, so much so that programmers are encouraged to <a href="http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism">replace them with polymorphism</a> where possible. </p>

<p>This anti-switching bias is based on the limited kind of switching allowed in languages such as Java. In Java.next, there is a different story. The Java.next languages all have powerful switching capabilities, allowing you to switch on <em>any criteria you like</em>. As an example, consider a method that calculates a letter grade, taking input that is either a number or letter grade. </p>

<h3>Ruby's case statement</h3>

<p>Here is <code>letter_grade</code> in Ruby:</p>

<pre><div class="codeblock"><code>def letter_grade(val)<br />&nbsp; case val<br />&nbsp;&nbsp;&nbsp; when 90..100: &#039;A&#039;<br />&nbsp;&nbsp;&nbsp; when 80...90:&nbsp; &#039;B&#039;<br />&nbsp;&nbsp;&nbsp; when 70...80:&nbsp; &#039;C&#039;<br />&nbsp;&nbsp;&nbsp; when 60...70:&nbsp; &#039;D&#039;<br />&nbsp;&nbsp;&nbsp; when 0...60:&nbsp;&nbsp; &#039;F&#039;<br />&nbsp;&nbsp;&nbsp; when /[ABCDF]/i: val.upcase<br />&nbsp;&nbsp;&nbsp; else raise &quot;Not a valid grade: #{val}&quot;<br />&nbsp; end<br />end</code></div></pre>

<p>In Ruby, the switch/case variant is called <code>case</code>. The Ruby <code>when</code> clause can take arbitrary expressions. Above you see ranges and regular expressions side-by-side in the same <code>case</code> expression. In general, the <code>when</code> clause expects objects that implement a well-known <em>threequals</em> method, <code>===</code>. Many Ruby objects have sensible <code>===</code> implementations: ranges match numbers in the range, regular expressions match  strings containing the regular expression, classes match instances of the class, etc. But <em>any</em> object can implement <code>===</code>, so you can implement arbitrarily complex dispatch with Ruby <code>case</code>.</p>

<h3>Groovy's switch statement</h3>

<p>Here is <code>letterGrade</code> in Groovy:</p>

<pre><div class="codeblock"><code>def letterGrade(val) {<br />&nbsp; switch(val) {<br />&nbsp;&nbsp; case 90..100: return &#039;A&#039;<br />&nbsp;&nbsp; case 80..&amp;lt;90:&nbsp; return &#039;B&#039;<br />&nbsp;&nbsp; case 70..&amp;lt;80:&nbsp; return &#039;C&#039;<br />&nbsp;&nbsp; case 60..&amp;lt;70:&nbsp; return &#039;D&#039;<br />&nbsp;&nbsp; case 0..&amp;lt;60:&nbsp;&nbsp; return &#039;F&#039;<br />&nbsp;&nbsp; case ~&quot;[ABCDFabcdf]&quot;: return val.toUpperCase()<br />&nbsp;&nbsp;&nbsp; default:&nbsp; throw new <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IllegalArgumentException(&quot;Invalid grade: $val&quot;)<br />&nbsp; }<br />}</code></div></pre>

<p>In Groovy, the switch/case variant is called <code>switch</code>. If you compare this code with JRuby, you will see minor syntactic differences:</p>

<ul>
<li>Groovy <code>switch</code> keeps faith with Java, so you have to <code>return</code> or <code>break</code> out                                                                        </li>

<li>Groovy uses <code>default</code> where Ruby uses <code>else</code>.</li>
<li>Groovy's top-exclusive range uses <code>..&amp;lt;</code> whereas Ruby's uses <code>...</code> .</li>
<li>Groovy uses <code>isCase</code> instead of <code>===</code>. (This is not visible in the code sample, but you would need it to test case matches individually.)</li>

</ul>

<p>The general ideas are the same. Both JRuby and Groovy provide far more powerful and general approaches than Java's <code>switch</code>.</p>

<h3>Clojure's cond function</h3>

<p>In clojure, as in many Lisps, you can switch on arbitrary functions using <code>cond</code>. One possible approach to letter-grade would be:</p>

<pre><div class="codeblock"><code>(defn letter-grade [grade]<br />&nbsp; (cond <br />&nbsp;&nbsp; (in grade 90 100) &quot;A&quot;<br />&nbsp;&nbsp; (in grade 80 90) &quot;B&quot;<br />&nbsp;&nbsp; (in grade 70 80) &quot;C&quot;<br />&nbsp;&nbsp; (in grade 60 70) &quot;D&quot;<br />&nbsp;&nbsp; (in grade 0 60) &quot;F&quot;<br />&nbsp;&nbsp; (re-find #&quot;[ABCDFabcdf]&quot; grade) (.toUpperCase grade)))</code></div></pre>

<p>In Clojure, regular expressions look like <code>#&quot;...&quot;</code>. The <code>in</code> function above is not part of Clojure. I wrote the code the way I wanted it to read, and then wrote this function:</p>

<pre><div class="codeblock"><code>(defn in [grade low high]<br />&nbsp;&nbsp; (and (number? grade) (&amp;lt;= low grade high)))</code></div></pre>

<p>In Clojure, I probably wouldn't use a regular expression for the letter-matching step, but I wrote the example that way for symmetry with the others.</p>

<p>Clojure's <code>cond</code> is just the tip of the iceberg. Clojure-contrib includes a set of macros for other variants of switch/case, and later in this article I will demonstrate Clojure's multiple dispatch.</p>

<h3>Scala's pattern matching</h3>

<p>Scala's pattern matching is a powerful generalization of the switch/case idiom in many programming languages. Scala provides out of the box support for pattern matching on</p>

<ul>
<li>constants</li>
<li>variables (which can be used in the match result)   </li>
<li>constructors                                        </li>
<li>sequences</li>
<li>tuples</li>

<li>types</li>
</ul>

<p>With pattern matching, implementing letterGrade is a snap:</p>

<pre><div class="codeblock"><code>val VALID_GRADES = Set(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;F&quot;)<br />def letterGrade(value: Any) : String = value match {<br />&nbsp; case x:Int if (90 to 100).contains(x) =&amp;gt; &quot;A&quot;<br />&nbsp; case x:Int if (80 to 90).contains(x) =&amp;gt; &quot;B&quot;<br />&nbsp; case x:Int if (70 to 80).contains(x) =&amp;gt; &quot;C&quot;<br />&nbsp; case x:Int if (60 to 70).contains(x) =&amp;gt; &quot;D&quot;<br />&nbsp; case x:Int if (0 to 60).contains(x) =&amp;gt; &quot;F&quot;<br />&nbsp; case x:String if VALID_GRADES(x.toUpperCase) =&amp;gt; x.toUpperCase()<br />}</code></div></pre>

<p>In this implementation, numeric grades and letter grades are both matched first by type. Then, case expressions also allow a <em>guard</em> that limits possible matches to some condition. So, for example, the first case above matches only if <code>value</code> is an <code>Int</code> (type match) and between 90 and 100 (the guard).</p>

<p>Scala's guard expressions are cool, but the combination of type+guard does not exactly parallel the other implementations of <code>letterGrade</code>, which rely on arbitrary predicates in case expressions. Scala can do this too: Scala <em>extractors</em> allow you to create arbitrary patterns. Here is one approach to <code>letterGrade</code> using extractors:</p>

<pre><div class="codeblock"><code>def letterGrade(value: Any) : String = value match {<br />&nbsp; case NumericA(value) =&amp;gt; &quot;A&quot;<br />&nbsp; case NumericB(value) =&amp;gt; &quot;B&quot;<br />&nbsp; case NumericC(value) =&amp;gt; &quot;C&quot;<br />&nbsp; case NumericD(value) =&amp;gt; &quot;D&quot;<br />&nbsp; case NumericF(value) =&amp;gt; &quot;F&quot;<br />&nbsp; case LetterGrade(value) =&amp;gt; value<br />}</code></div></pre>

<p>Behind the scenes, <code>NumericA</code> and friends are objects that implement an <code>unapply</code> method to determine if and how a value should match the pattern.</p>

<h3>A more complex example</h3>

<p>Scala's pattern matching is much more general than the letter grade example shows. To see this, check out Daniel Spiewak's series introducing Scala for Java programmers. In <a href="http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4">Part 4</a>, he gives an example of pattern-matching working in conjunction with <em>case classes</em>, which I will explore below.</p>

<h3>Scala's case classes</h3>

<p>Case classes offer several interesting properties when compared to regular classes:</p>

<ul>
<li>Case classes automatically get a factory method, e.g. <code>Foo(1)</code> instead of <code>new Foo(1)</code></li>
<li>Case classes automatically get reasonable implementations for <code>toString</code>, <code>hashCode</code>, and <code>equals</code>.</li>
</ul>

<p>These properties are so useful that Scala programmers use case classes for all kinds of things. But their true purpose is revealed in conjunction with patterns: <em>Case classes work directly with pattern matching</em>, without having to write an extractor as in the previous example.</p>

<pre><div class="codeblock"><code>class Color(val red:Int, val green:Int, val blue:Int)<br /><br />case class Red(r:Int) extends Color(r, 0, 0)<br />case class Green(g:Int) extends Color(0, g, 0)<br />case class Blue(b:Int) extends Color(0, 0, b)<br /><br />def printColor(c:Color) = c match {<br />&nbsp; case Red(v) =&amp;gt; println(&quot;Red: &quot; + v)<br />&nbsp; case Green(v) =&amp;gt; println(&quot;Green: &quot; + v)<br />&nbsp; case Blue(v) =&amp;gt; println(&quot;Blue: &quot; + v)<br /><br />&nbsp; case col:Color =&amp;gt; {<br />&nbsp;&nbsp;&nbsp; print(&quot;R: &quot; + col.red + &quot;, &quot;)<br />&nbsp;&nbsp;&nbsp; print(&quot;G: &quot; + col.green + &quot;, &quot;)<br />&nbsp;&nbsp;&nbsp; println(&quot;B: &quot; + col.blue)<br />&nbsp; }<br /><br />&nbsp; case null =&amp;gt; println(&quot;Invalid color&quot;)<br />}</code></div></pre>

<p>The <code>printColor</code> method pattern-matches <code>Red</code>, <code>Green</code>, and <code>Blue</code> to provide special behavior for basic colors. Because these are case classes we can capture the actual color value <code>v</code>. All other colors fall through to a general <code>Color</code>, which prints a more generic message.</p>

<h3>Clojure's defmulti</h3>

<p>Scala's pattern-matching is a signature feature of the language. How do the other Java.next languages compare? To implement <code>printColor</code> in Clojure, I begin by defining a structure to capture a color:</p>

<pre><div class="codeblock"><code>(defstruct color :red :green :blue)</code></div></pre>

<p>Where the Scala example defined basic colors with case classes, in Clojure I can use functions:</p>

<pre><div class="codeblock"><code>(defn red [v] (struct color v 0 0))<br />(defn green [v] (struct color 0 v 0))<br />(defn blue [v] (struct color 0 0 v))</code></div></pre>

<p>Now for the fun part. I will define a multimethod named <code>color-string</code>, which dispatches based on which basic colors are present in the color struct.</p>

<pre><div class="codeblock"><code>(defmulti color-string basic-colors-in)</code></div></pre>

<p><code>basic-colors-in</code> is a dispatch function that reports which colors have nonzero values:</p>

<pre><div class="codeblock"><code>(defn basic-colors-in [color]<br />&nbsp; (for [[k v] color :when (not= v 0)] k))</code></div></pre>

<p>Now I can define multiple implementations of <code>color-string</code>. The basic syntax is </p>

<pre><div class="codeblock"><code>(defmethod method-name dispatch-value function-body)</code></div></pre>

<p>So for the three pure colors, I can define color-string as </p>

<pre><div class="codeblock"><code>(defmethod color-string [:red] [color] (str &quot;Red: &quot; (:red color)))<br />(defmethod color-string [:green] [color] (str &quot;Green: &quot; (:green color)))<br />(defmethod color-string [:blue] [color] (str &quot;Blue: &quot; (:blue color)))</code></div></pre>

<p>I can also provide a catch-all implementation by specifying a dispatch-value of <code>:default</code>:</p>

<pre><div class="codeblock"><code>(defmethod color-string :default [color] <br />&nbsp; (str &quot;Red: &quot; (:red color) &quot;, Green: &quot; (:green color) &quot;, Blue: &quot; (:blue color)))</code></div></pre>

<p>Multimethods are more powerful than polymorphic single dispatch in two important ways:</p>

<ol>
<li>With polymorphic single dispatch, the dispatch function is always the type of the the first argument. With multimethods, the dispatch function can be any arbitrary function, e.g. <code>basic-colors-in</code> above.</li>
<li>With polymorphic single dispatch, polymorphism is limited to the first parameter. The dispatch function for a multimethod can look at all parameters, and vary based on any of them. (This feature is not needed in the <code>color-string</code> example above, but see <a href="http://clojure.org/runtime_polymorphism">Runtime Polymorphism</a> for an example.)</li>

</ol>

<p>Like Scala's pattern matching, Clojure's <code>defmulti</code> provides an extremely powerful and extensible dispatch mechanism.</p>

<h3>Accidently blue</h3>

<p>Both the Scala and Clojure code above take special action for colors that are declared to be pure blue:</p>

<pre><div class="codeblock"><code>// Scala<br />scala&amp;gt; printColor(Blue(10))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />Blue: 10<br /><br />; Clojure<br />user=&amp;gt; (color-string (blue 10))<br />&quot;Blue: 10&quot;</code></div></pre>

<p>What about colors that are not <em>declared</em> as blue, but are, nevertheless, purely blue. These colors are <em>accidentally blue</em>:</p>

<pre><div class="codeblock"><code>// different result for accidental blues<br />scala&amp;gt; printColor(new Color(0, 0, 10))<br />R: 0, G: 0, B: 10<br /><br />; all blues equal<br />user=&amp;gt; (color-string (struct color 0 0 10))<br />&quot;Blue: 10&quot;</code></div></pre>

<p>The Scala example was written to dispatch based on type, so it treats accidentally blue colors different from "real" <code>Blue</code>s. The Clojure example, on the other hand, dispatches based on the actual color values, so all solid blues are treated the same, no matter how they are created.</p>

<p>Of course, nothing stops me from "fixing" the Scala example, e.g. by dispatching on something other than type:</p>

<pre><div class="codeblock"><code>case class Color(val red:Int, val green:Int, val blue:Int)<br /><br />object ColorDemo {<br />&nbsp; def colorString(c:Color) = c match {<br />&nbsp;&nbsp;&nbsp; case Color(r,0,0) =&amp;gt; &quot;Red: &quot; + r<br />&nbsp;&nbsp;&nbsp; case Color(0,g,0) =&amp;gt; &quot;Green: &quot; + g<br />&nbsp;&nbsp;&nbsp; case Color(0,0,b) =&amp;gt; &quot;Blue: &quot; + b<br /><br />&nbsp; case col:Color =&amp;gt; {<br />&nbsp;&nbsp;&nbsp; &quot;R: &quot; + col.red + &quot;, &quot; +<br />&nbsp;&nbsp;&nbsp; &quot;G: &quot; + col.green + &quot;, &quot; +<br />&nbsp;&nbsp;&nbsp; &quot;B: &quot; + col.blue<br />&nbsp; }<br /><br />&nbsp; case null =&amp;gt; &quot;Invalid color&quot;<br />&nbsp;&nbsp;&nbsp; case null =&amp;gt; &quot;Invalid color&quot;<br />&nbsp; }<br />}</code></div></pre>

<p>Or, I could "break" the Clojure example by adding a type tag, and dispatching on that instead. Rich Hickey posted <a href="http://groups.google.com/group/clojure/browse_thread/thread/4b776a3c58fbb2d2/c230eb442338f89f?lnk=gst&amp;q=color-string#c230eb442338f89f">this example</a> on the Clojure mailing list:</p>

<pre><div class="codeblock"><code>(defstruct color :red :green :blue)<br /><br />(defn color-class [name r g b]<br /> (assoc (struct color r g b) :tag name))<br /><br />(defn red [v] (color-class :red&nbsp; v 0 0))<br />(defn green [v] (color-class :green 0 v 0))<br />(defn blue [v] (color-class :blue 0 0 v))<br />(defmulti color-string :tag)<br />(defmethod color-string :red [c] (str &quot;Red: &quot; (:red c)))<br />(defmethod color-string :green [c] (str &quot;Green: &quot; (:green c)))<br />(defmethod color-string :blue [c] (str &quot;Blue: &quot; (:blue c)))<br />(defmethod color-string :default [{:keys [red green blue]}]<br />&nbsp;&nbsp; (str &quot;Color, R: &quot; red &quot;, G: &quot; green &quot;, B: &quot; blue))</code></div></pre>

<p>This version now works like the original Scala version, treating "accidental" blue differently from things marked with a <code>:tag</code> of <code>:blue</code>.</p>

<p>Note that multimethods are <em>open</em>. I can add new colors later without having to modify the existing code:</p>

<pre><div class="codeblock"><code>(defn orange [r g] (color-class :orange r g 0))<br />(defmethod color-string :orange [{:keys [red green]}]<br />&nbsp;&nbsp; (str &quot;Orange, R: &quot; red &quot;, G: &quot; green))</code></div></pre>

<h3>Dynamic Scala?</h3>

<p>If you are a dynamic language programmer fearing the tyranny of the Scala compiler, pattern matching is a cause for rejoicing. With pattern matching, you can bypass static typing and get the flexibility of much more dynamic dispatch. Consider: Scala's pattern matching can be used to dispatch on arbitrary predicates. These predicates are not limited to type relationships known at compile time, so a Scala program that uses pattern matching as the cornerstone of its dispatch strategy can be as dynamic as an <em>extremely</em> dynamic Ruby program. Put another way: Scala's catch-all match default (<code>_</code>) is the moral equivalent of Ruby's <code>method_missing</code>.</p>

<h3>Conclusions</h3>

<p>Dispatch takes many forms. Single dispatch, switch statements, pattern matching, and multiple dispatch all meet similar needs: Selecting runtime behavior in response to varying runtime conditions.   </p>

<p>Flexible dispatch is a key element of Java.next. All of the Java.next languages support dispatch strategies that are far more flexible than Java's single dispatch. These strategies are not perfectly interchangeable, but have a great degree of overlap. For example, Clojure's multimethods and Scala's pattern matching look quite different on the surface but can be used to solve similar problems.</p>

<p>Dispatch can be based on criteria more dynamic than the type system, even in Scala.</p>

<h3>Notes</h3>

<ul>

<li>This article is based on the <a href="http://blog.thinkrelevance.com/2008/6/13/jvm-language-shootout-clojure-jruby-and-scala">JVM Language Shootout</a> talk. Check the <a href="http://thinkrelevance.com/events">schedule</a> for a talk near you.</li>
<li>Thanks to Ola Bini, Justin Gehtland, Jason Rudolph, Daniel Spiewak, Venkat Subramaniam, and Greg Vaughn for their feedback on a draft of this article.</li>
<li>Thanks to Chouser and Rich Hickey for feedback on the Clojure examples.</li>
<li>Feedback on how to improve these examples is most welcome!</li>
</ul>

<h3>Revision History</h3>

<ul>
<li>2008/08/29. Fixed fencepost error in Groovy code (Thanks Scott!). How irritating -- I have working unit tests for all the code and get burned by copy and paste.</li>
<li>2008/08/30. Better Scala pattern match in second example, per Stefan's suggestion.</li>
</ul>    ]]></content>
  </entry>
  <entry>
    <title>Java.next #2: Java interop</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/1260" />
    <id>http://www.javaworld.com/community/node/1260</id>
    <published>2008-08-20T16:39:54-04:00</published>
    <updated>2008-08-20T16:39:54-04:00</updated>
    <author>
      <name>stuart_halloway</name>
    </author>
    <category term="Dynamic Languages" />
    <category term="interoperability" />
    <category term="Java.next" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>This is Part Two of a series of articles on Java.next. In Part Two, I will look at how Java.next languages interoperate with Java.</p>

<p>Java interop is trivial in all of the Java.next languages. We have Java itself to thank for this--the Java Virtual Machine Specification makes it easy for other languages to reflect against and call Java code.</p>

<h3>A Swing example</h3>

<p>As a first example, consider calling into the Java Swing API to create an application [1] that has</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>This is Part Two of a series of articles on Java.next. In Part Two, I will look at how Java.next languages interoperate with Java.</p>

<p>Java interop is trivial in all of the Java.next languages. We have Java itself to thank for this--the Java Virtual Machine Specification makes it easy for other languages to reflect against and call Java code.</p>

<h3>A Swing example</h3>

<p>As a first example, consider calling into the Java Swing API to create an application [1] that has</p>

<ul>
<li>a frame</li>
<li>button</li>
<li>a button handler that responds with a model dialog        </li>
</ul>

<p>For starters, here is the application in plain old Java:</p>

<pre><div class="codeblock"><code>// Java<br />import javax.swing.JFrame;<br />import javax.swing.JButton;<br />import javax.swing.JOptionPane;<br />import java.awt.event.ActionListener;<br />import java.awt.event.ActionEvent;<br /><br />public class Swing {<br />&nbsp; public static void main(String[] args) {<br />&nbsp;&nbsp;&nbsp; JFrame frame = new JFrame(&quot;Hello Swing&quot;);<br />&nbsp;&nbsp;&nbsp; JButton button = new JButton(&quot;Click Me&quot;);<br /><br />&nbsp;&nbsp;&nbsp; button.addActionListener(new ActionListener() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void actionPerformed(ActionEvent event) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JOptionPane.showMessageDialog(null,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String.format(&quot;&amp;lt;html&amp;gt;Hello from &amp;lt;b&amp;gt;Java&amp;lt;/b&amp;gt;&amp;lt;br/&amp;gt;&quot; +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;Button %s pressed&quot;, event.getActionCommand()));<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; });<br />&nbsp;&nbsp;&nbsp; frame.getContentPane().add(button);<br />&nbsp;&nbsp;&nbsp; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />&nbsp;&nbsp;&nbsp; frame.pack();<br />&nbsp;&nbsp;&nbsp; frame.setVisible(true);<br />&nbsp; }<br />}</code></div></pre>

<p>Below, I will present the same Swing application, ported to the Java.next languages. Please take note of two things about these examples:</p>

<ul>
<li>For this post, I am presenting the languages in order of increasing syntactic distance from Java. This makes sense for porting a simple example from the well-known to the increasingly unfamiliar.</li>
<li>The ports below are <em>not best practice</em> in the Java.next languages. They are deliberately simplistic, so that I can focus on Java interop. In later installments of this series I will show more idiomatic Java.next code. </li>
</ul>

<h3>Groovy Swing example</h3>

<p>Groovy is the Java.next language that looks most like Java. Here is the same example in Groovy:</p>

<pre><div class="codeblock"><code>// Groovy<br />import javax.swing.JFrame<br />import javax.swing.JButton<br />import javax.swing.JOptionPane<br />import java.awt.event.ActionListener<br /><br />frame = new JFrame(&quot;Hello Swing&quot;)<br />button = new JButton(&quot;Click Me&quot;)<br /><br />button.addActionListener({<br />&nbsp; JOptionPane.showMessageDialog(null, &quot;&quot;&quot;&amp;lt;html&amp;gt;Hello from &amp;lt;b&amp;gt;Groovy&amp;lt;/b&amp;gt;<br />Button ${it.actionCommand} pressed&quot;&quot;&quot;)<br />} as ActionListener) <br />frame.contentPane.add button<br /><br />frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE<br />frame.pack()<br />frame.visible = true</code></div></pre>

<p>If you compare this to the Java example, it is almost the same code, minus a bunch of unnecessary ceremony. The Groovy version lets us omit:</p>

<ul>
<li>semicolons</li>
<li>type declarations</li>
<li>most parentheses </li>
<li><code>get</code> and <code>set</code> for property access</li>
</ul>

<p>The most important benefit, however, comes in the action listener. The Groovy version sports</p>

<ul>
<li>a multiline string (delimited by """)</li>
<li>string interpolation of <code>it.actionCommand</code> (inside ${})</li>
<li>no need to write an anonymous inner class, simply pass an anonymous function</li>
</ul>

<p>For a more idiomatic approach to Swing in Groovy, see the Groovy <a href="http://groovy.codehaus.org/Swing+Builder">SwingBuilder</a> project.  </p>

<p>Since this post is about Java interop I will state the obvious: From Groovy, Java interop is entirely trivial.</p>

<h3>Scala Swing example</h3>

<p>Next, let's look at the Scala version:</p>

<pre><div class="codeblock"><code>// Scala (almost right, see below)<br />import javax.swing._<br />import java.awt.event.{ActionEvent, ActionListener}<br /><br />object HelloWorld extends JFrame(&quot;Hello Swing&quot;) {<br />&nbsp; def showButtonMessage(msg: String)&nbsp; =<br />&nbsp;&nbsp;&nbsp; JOptionPane.showMessageDialog(null, String.format(&quot;&quot;&quot;&amp;lt;html&amp;gt;Hello from &amp;lt;b&amp;gt;Scala&amp;lt;/b&amp;gt;. Button %s pressed&quot;&quot;&quot;, Array(msg)));<br /><br />&nbsp; def main(args: Array[String]) {<br />&nbsp;&nbsp;&nbsp; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)<br />&nbsp;&nbsp;&nbsp; val button = new JButton(&quot;Click Me&quot;)<br />&nbsp;&nbsp;&nbsp; button.addActionListener((e:ActionEvent) =&amp;gt; showButtonMessage(e.getActionCommand.toString))<br />&nbsp;&nbsp;&nbsp; getContentPane add button<br />&nbsp;&nbsp;&nbsp; pack<br />&nbsp;&nbsp;&nbsp; setVisible(true)<br />&nbsp; }<br />}</code></div></pre>

<p>The Scala version offers many of the same advantages over Java that the Groovy version provided:</p>

<ul>
<li>fewer type declarations than Java</li>
<li>fewer semicolons</li>
<li>fewer parentheses</li>
</ul>

<p>We also see a few items unique to Scala:</p>

<ul>
<li>In Scala, the import wildcard is <code>_</code>, not <code>*</code>. In Scala, <code>*</code> is a valid identifier. (Scala's punctuation-friendly identifiers will be a big advantage later when I am writing DSLs.)  </li>
<li>Scala has an inline syntax for importing multiple classes in a package.</li>
<li>Since we only need one, we declare an <code>object</code> instead of a <code>class</code>.</li>

<li>Our object extends JFrame, and Scala lets us call the JFrame constructor inline, instead of having to declare a separate constructor.</li>
</ul>

<p>Again, the most important differences are in the action listener. Like Groovy, Scala lets us skip the anonymous inner class ritual, and simply pass a function:</p>

<pre><div class="codeblock"><code>button.addActionListener((e:ActionEvent) =&amp;gt; <br />&nbsp; showButtonMessage(e.getActionCommand.toString))</code></div></pre>

<p>That looks great, except I cheated a little. Scala's implementation of strong typing won't automatically coerce a function into an <code>ActionListener</code>, so the above code won't compile out of the box. Fortunately, Scala's implicit conversions let us have our cake and eat it too: strong typing <em>plus</em> much of the syntactic convenience of a looser type system. All we have to do is tell Scala the the conversion is legal:</p>

<pre><div class="codeblock"><code>// Yes, we can<br />implicit def actionPerformedWrapper(func: (ActionEvent) =&amp;gt; Unit) = <br />&nbsp; new ActionListener { def actionPerformed(e:ActionEvent) = func(e) }</code></div></pre>

<p>With this one-time setup in place, we can now pass a function where an <code>ActionListener</code> is expected. </p>

<p>There seem to be several projects to wrap Swing in more idiomatic Scala. Using one of these libraries you should be able to get a syntax cleaner than the sample code here. See <a href="http://scala.sygneca.com/code/scalagui">ScalaGUI</a> for one example.</p>

<p>From Scala, Java interop is trivial.</p>

<h3>JRuby Swing example</h3>

<p>Let's see how JRuby fares:</p>

<pre><div class="codeblock"><code>include Java<br />import javax.swing.JFrame<br />import javax.swing.JButton<br />import javax.swing.JOptionPane<br />import java.awt.event.ActionListener<br /><br />button = JButton.new &quot;Click Me&quot;<br />button.add_action_listener do |evt|<br />&nbsp; JOptionPane.showMessageDialog(nil, &amp;lt;&amp;lt;-END)<br />&amp;lt;html&amp;gt;Hello from &amp;lt;b&amp;gt;JRuby&amp;lt;/b&amp;gt;.<br />Button &#039;#{evt.getActionCommand()}&#039; clicked.<br />END<br />end<br /><br />frame = JFrame.new &quot;Hello Swing&quot;<br />frame.content_pane.add button<br />frame.default_close_operation = JFrame::EXIT_ON_CLOSE<br />frame.pack<br />frame.visible = true</code></div></pre>

<p>If you compare this to the earlier Groovy example, you will see almost exactly the same feature set:</p>

<ul>
<li>fewer type declarations</li>
<li>fewer semicolons</li>
<li>fewer parentheses</li>
<li>simplified property access (no <code>get</code> or <code>set</code>)</li>

<li>a multiline string (delimited by END)</li>
<li>string interpolation of <code>evt.getActionCommand</code> (the stuff inside #{})</li>
</ul>

<p>The action listener callback is simplified in a fashion similar to the Groovy example. Ruby automatically generates the <code>ActionListener</code> from a block: </p>

<pre><div class="codeblock"><code>button.add_action_listener { |evt|<br />&nbsp; # do stuff<br />}</code></div></pre>

<p>In the JRuby example I used Ruby conventions for method names, even on Java objects:</p>

<pre><div class="codeblock"><code># Ruby<br />frame.content_pane</code></div></pre>

<p>Java programmers expect camel case. As a convenience, JRuby supports <em>both</em> naming conventions:     </p>

<pre><div class="codeblock"><code># Groovy, Scala, or JRuby<br />frame.contentPane</code></div></pre>

<p>Ruby's flexibility has encouraged a lot of experimentation with alternate syntaxes for Java interop. See <a href="http://jira.codehaus.org/browse/JRUBY-903">JRUBY-903</a> for some of the history. For a more idiomatic approach to Swing in JRuby, see the <a href="http://ihate.rubyforge.org/profligacy">Profligacy</a> project. </p>

<p>From JRuby, Java interop is trivial.</p>

<h3>Clojure Swing example</h3>

<p>Here is the Clojure version:</p>

<pre><div class="codeblock"><code>; Clojure <br />; Clojure<br />(import &#039;(javax.swing JFrame JButton JOptionPane))<br />(import &#039;(java.awt.event ActionListener))<br /><br />(let [frame (JFrame. &quot;Hello Swing&quot;)<br />&nbsp;&nbsp;&nbsp;&nbsp; button (JButton. &quot;Click Me&quot;)]<br /> (.addActionListener button<br />&nbsp;&nbsp; (proxy [ActionListener] []<br />&nbsp;&nbsp;&nbsp;&nbsp; (actionPerformed [evt]<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (JOptionPane/showMessageDialog&nbsp; nil,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (str &quot;&amp;lt;html&amp;gt;Hello from &amp;lt;b&amp;gt;Clojure&amp;lt;/b&amp;gt;. Button &quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (.getActionCommand evt) &quot; clicked.&quot;)))))<br /><br /> (.. frame getContentPane (add button))<br /> (doto frame<br />&nbsp;&nbsp; (setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)<br />&nbsp;&nbsp; pack<br />&nbsp;&nbsp; (setVisible true)))</code></div></pre>

<p>Because Clojure is a Lisp, the syntax is radically different from the others. This deserves hours of discussion, or none. Since my focus here is on Java interop, I am going to save The Great Parenthesis Debate for a later entry in this series. For now, let us suspend judgment on syntax, and focus exclusively on the Java interop.</p>

<p>Importing Java classes is easy. <code>import</code> takes a list. The first element of the list is a package, and the remaining elements are classes to add to the current namespace. Note that this allows the import of multiple classes in a single line.</p>

<pre><div class="codeblock"><code>(import &#039;(javax.swing JFrame JButton JOptionPane))</code></div></pre>

<p>Creating a Java instance is easy. Use the <code>(class. &amp;amp;args)</code> form.</p>

<pre><div class="codeblock"><code>(JFrame. &quot;Hello Swing&quot;)</code></div></pre>

<p>There are multiple ways to call methods on a Java class. If you want to call a single method, you can use the <code>(.methodName obj &amp;amp;args)</code> form. For static calls, you can also use the <code>(class/method &amp;amp;args)</code> form:</p>

<pre><div class="codeblock"><code>(JOptionPane/showMessageDialog nil &quot;A message&quot;)</code></div></pre>

<p>Sometimes you want to chain multiple calls together. Where in Java you would say <code>x.y().z()</code>, in Clojure you can use the <code>(.. x (y) (z))</code> form.</p>

<pre><div class="codeblock"><code>(.. frame (getContentPane) (add button))</code></div></pre>

<p>The last three method calls in our example are all on the same <code>frame</code> object. With Clojure's <code>doto</code> form, you can perform multiple operations on an object without having to repeat the object each time.</p>

<pre><div class="codeblock"><code>(doto frame<br />&nbsp; (setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)<br />&nbsp; pack<br />&nbsp; (setVisible true)))</code></div></pre>

<p>As with the other examples, the action listener is the most interesting part. In Clojure, <code>proxy</code> will dynamically create a Java instance [2], allowing you to implement interfaces and methods as needed.</p>

<pre><div class="codeblock"><code>(proxy [ActionListener] []<br />&nbsp; (actionPerformed [evt] {do stuff here...}))</code></div></pre>

<p>As with JRuby, this solution is more general, and requires more syntax, than the Groovy approach. Also as with JRuby, you can easily roll your own syntax.</p>

<p>From Clojure, Java interop is trivial.</p>

<h3>Try this at home</h3>

<p>The interop story in Java.next is almost boring: It Just Works. So to spice things up a little, here is an exercise in rolling your own constructs, inspired by the examples above. Consider Clojure's <code>import</code>,  which can import multiple Java classes in a single line of code. </p>

<pre><div class="codeblock"><code>(import &#039;(javax.swing JFrame JButton JOptionPane))</code></div></pre>

<p>Why can't this be even more general? Try your hand at writing a custom import function in one of the Java.next languages. Some useful features might be</p>

<ul>
<li>import all the classes in a JAR</li>

<li>import all the classes in the intersection of a package and a JAR </li>
<li>import only interfaces</li>
<li>import all classes macthing some criteria</li>
<li>import all classes except those matching some criteria</li>
</ul>

<p>Let me know what you come up with, and I will link to it here.</p>

<h3>Conclusion</h3>

<p>In the examples above, I have demonstrated how all of the Java.next libraries can trivially interoperate with Java. Each of examples called the Swing library with fewer lines of code than the Java version. More importantly, the Java.next versions capture the essence of the program with less ceremony. </p>

<p>Seamless interoperation with Java should not be the primary yardstick when measuring Java.next languages, because they all get it right. There are complexities and corner cases beyond what I have shown here, in <em>all</em> of the Java.next languages. But I consider the Java interop problem to be basically solved. </p>

<p>In these first two articles, I have stayed fairly close to Java style while demonstrating Java.next language features. With that groundwork in place, it is time to start using idiomatic Java.next. In the next installment of the Java.next series, we will look at how the Java.next languages support Domain-Specific Languages.</p>

<h3>Notes</h3>

<ul>
<li>This series is taken from the <a href="http://blog.thinkrelevance.com/2008/6/13/jvm-language-shootout-clojure-jruby-and-scala">JVM Language Shootout</a> talk. Check the <a href="http://thinkrelevance.com/events">schedule</a> for a talk near you.</li>

<li>Suggestions for improving the code samples above are most welcome.</li>
<li>Thanks to Jason Rudolph, Glenn Vanderburg, and Greg Vaughn for reading an earlier draft of this article.</li>
</ul>

<h3>Footnotes</h3>

<ol>
<li>I took the Swing application example from the JRuby samples, and ported it to the other Java.next languages.</li>
<li>Clojure's <code>proxy</code> creates classes as necessary behind the scenes. In Java.next, the dichotomy of class and object is not constantly center stage.</li>

</ol>

<h3>Revisions</h3>

<ul>
<li>2008/08/14. Updated Clojure example and prose per <a href="http://clojure.org/">Rich Hickey</a>'s suggestion. Updated Groovy example to include pointer to SwingBuilder, per <a href="http://www.jroller.com/aalmiray/">Andres Almiray</a>. Updated JRuby example and prose based on suggestions from <a href="http://blog.nicksieger.com/">Nick Sieger</a> and <a href="http://ola-bini.blogspot.com/">Ola Bini</a>. Updated Scala example per Tony Morris's <a href="http://blog.tmorris.net/java-interop-errata/">suggestion</a>. Thanks for all the improvements!</li>

</ul>     ]]></content>
  </entry>
  <entry>
    <title>Java.next: Common Ground</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/1047" />
    <id>http://www.javaworld.com/community/node/1047</id>
    <published>2008-08-11T16:42:50-04:00</published>
    <updated>2008-08-12T17:50:47-04:00</updated>
    <author>
      <name>stuart_halloway</name>
    </author>
    <category term="java" />
    <category term="Java.next" />
    <category term="languages" />
    <summary type="html"><![CDATA[<p>This is Part One of a series of articles on Java.next. In Part One, I will explore the common ground shared by the Java.next languages.</p>
<p>I have chosen four languages which together represent "Java.next": Clojure, Groovy, JRuby, and Scala. At first glance, these languages are wildly different. Clojure is a Lisp. Groovy is the "almost Java" choice. JRuby has the beauty of Ruby, and the mindshare of Rails. Scala, unlike the others, brings the notion that we need <em>more</em> static typing.</p>
    ]]></summary>
    <content type="html"><![CDATA[<p>This is Part One of a series of articles on Java.next. In Part One, I will explore the common ground shared by the Java.next languages.</p>
<p>I have chosen four languages which together represent "Java.next": Clojure, Groovy, JRuby, and Scala. At first glance, these languages are wildly different. Clojure is a Lisp. Groovy is the "almost Java" choice. JRuby has the beauty of Ruby, and the mindshare of Rails. Scala, unlike the others, brings the notion that we need <em>more</em> static typing.</p>
<p>As you might imagine, there is heated debate about which of these languages is best for some purpose, or best in general. Lost in the debate is the fact that these languages share a ton of common ground. They all evolved against a shared background, the Java language. Their design decisions are all influenced by what has worked well in Java, and what has failed.</p>
<p>In this article I will demonstrate two important points about the common ground these languages share:</p>
<ul>
<li>Over the last decade of coding in object-oriented, VM-based languages, we have learned a lot about writing expressive, maintainable applications. Java.next incorporates this knowledge, enabling <a href="http://blog.thinkrelevance.com/2008/4/1/ending-legacy-code-in-our-lifetime">essence over ceremony</a>.</li>
<li>The "essence vs. ceremony" design choices add up to a very different way of programming. The mental shift from Java to Java.next is a bigger shift than the previous shift from C/C++ to Java.</li>
</ul>
<p>I have distilled the shared advantages of Java.next to eight points, which are explored in more detail below.</p>
<ul>
<li>everything is an object</li>
<li>low-ceremony property definitions</li>
<li>expressive collections</li>
<li>functional programming</li>
<li>overriding operators</li>
<li>maintainable exception handling</li>
<li>adding methods to existing objects</li>
<li>roll-your-own constructs</li>
</ul>
<h3>Everything is an object</h3>
<p>In Java, we live every day with the distinction between objects and primitives. This causes three practical problems:</p>
<ol>
<li>APIs must be duplicated: one method for objects, and another for primitives. Or worse, septlicated. One method for objects, and one each for different primitive types.</li>
<li>The default (efficient, easy-to-use) numeric types have range limitations. Exceed them and your program breaks in mysterious ways.</li>
<li>You cannot use intuitive math operators (+,-,etc.) with accurate numeric types.</li>
</ol>
<p>In Java.next, everything is an object. You can invoke methods on all types using the same syntax.</p>
<pre><div class="codeblock"><code>; clojure<br />(. 1 floatValue)<br />1.0<br /><br />// groovy<br />1.floatValue()<br />===&amp;gt; 1.0<br /><br /># ruby<br />1.to_f<br />=&amp;gt; 1.0<br /><br />// scala<br />1.floatValue<br />res1: Float = 1.0</code></div></pre><h3>Low-ceremony property definitions</h3>
<p>In Java, to create a property, you must define a field, a getter, a setter, and (often) a constructor, all with appropriate protection modifiers. In Java.next, you can define all of these in a single step.</p>
<pre><div class="codeblock"><code>; clojure<br />(defstruct person :first-name :last-name)<br /><br />// groovy<br />class Person {<br />&nbsp;&nbsp;&nbsp; def firstName<br />&nbsp;&nbsp;&nbsp; def lastName<br />}<br /><br /># ruby<br />Person = Struct.new(:first_name, :last_name)<br /><br />// scala<br />case class Person(firstName: String, lastName: String) {}</code></div></pre><p>If you need to override (or omit) a getter, setter, or constructor for a class, you can also do that, without having to spell out all boilerplate versions of the other pieces.</p>
<p>And that's not all. All of these languages embrace TMTOWTDI (There's More Than One Way To Do It), so there are multiple variants on the approaches shown above.   </p>
<h3>Expressive collections</h3>
<p>Java.next provides a convenient literal syntax for the most important collections: arrays and maps. In addition, you can string together multiple operations by passing function arguments, without having to write explicit iterators or loops. For example, to find the all the squares under 100 that are also odd:</p>
<pre><div class="codeblock"><code>; clojure<br />(filter (fn [x] (= 1 (rem x 2))) (map (fn [x] (* x x)) (range 10)))<br />(1 9 25 49 81)<br /><br />// groovy<br />(1..10).collect{ it*it }.findAll { it%2 == 1}<br />===&amp;gt; [1, 9, 25, 49, 81]<br /><br /># ruby<br />(1..10).collect{ |x| x*x }.select{ |x| x%2 == 1}<br />=&amp;gt; [1, 9, 25, 49, 81]<br /><br />// scala<br />(1 to 10).map(x =&amp;gt; x*x).filter(x =&amp;gt; x%2 == 1)<br />res20: Seq.Projection[Int] = RangeMF(1, 9, 25, 49, 81)</code></div></pre><p>There are similar conveniences for name/value collections, a.k.a. hashes or dictionaries.</p>
<h3>Functional programming</h3>
<p>The convenient collections described above are a special case of a more general idea: functional programming. Java.next supports functions as first class objects, allowing function arguments, functions that create new functions, and closures over the current scope. As a simple example, consider creating an adder function that adds some value chosen at runtime:</p>
<pre><div class="codeblock"><code>; clojure<br />(defn adder [x] (fn [y] (+ x y)))<br /><br />// groovy<br />adder = { add -&amp;gt; { val -&amp;gt; val + add } } <br /><br /># ruby<br />def adder(add)<br />&nbsp; lambda { |x| x + add }<br />end<br /><br />// scala<br />def sum(a: Int)(b: Int) = a + b</code></div></pre><h3>Overriding operators</h3>
<p>In Java, you cannot override operators. Math looks like this, for types like BigDecimal:</p>
<pre><div class="codeblock"><code>// Java math<br />balance.add(balance.multiply(interest));</code></div></pre><p>Java.next allows you to override operators. This allows you to do create new types that feel like built-in types, e.g. you could write a <code>ComplexNumber</code> or <code>RationalNumber</code> that supports +, -, *, and /.</p>
<pre><div class="codeblock"><code>; Clojure<br />(+ balance (* balance interest))<br /><br />// Groovy<br />balance + (balance * interest)<br /><br /># JRuby<br />balance + (balance * interest)<br /><br />// Scala (See [1])<br />balance + (balance * interest)</code></div></pre><h3>Maintainable exception handling</h3>
<p>Checked exceptions are a failed experiment. Java code is bloated with checked exception handling code that tends to obscure intent without improving error handling. Worse yet, checked exceptions are a maintenance headache at abstraction boundaries. (New kinds of unrecoverable failures down the dependency chain should not necessitate recompilation!)</p>
<p>Java.next does not require you to declare checked exceptions, or to explicitly deal with checked exceptions from other code. It is a testimony to the power of Java (the platform) that other languages are free to ignore the ugliness of checked exceptions in Java (the language).</p>
<h3>Adding methods to existing types</h3>
<p>In Java, you cannot add methods to existing types. This leads to absurd object-mismodeling, as developers create utility classes that defy the point of OO:</p>
<pre><div class="codeblock"><code>// Java (from the Jakarta Commons)<br />public class StringUtils { <br />&nbsp; public static boolean isBlank(String str) { <br />&nbsp;&nbsp;&nbsp; int strLen; <br />&nbsp;&nbsp;&nbsp; if (str == null || (strLen = str.length()) == 0) { <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return true; <br />&nbsp;&nbsp;&nbsp; }&nbsp; <br />&nbsp;&nbsp;&nbsp; for (int i = 0; i &amp;lt; strLen; i++) { <br />&nbsp;&nbsp;&nbsp; if ((Character.isWhitespace(str.charAt(i)) == false)) { <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false; <br />&nbsp;&nbsp;&nbsp; } <br />&nbsp; }<br />}</code></div></pre><p>In Java.next, you can add methods to existing types:</p>
<pre><div class="codeblock"><code>; Clojure<br />(defmulti blank? class)<br />(defmethod blank? String [s] (every? #{\space} s))<br />(defmethod blank? nil [_] true)<br /><br />// Groovy<br />String.metaClass.isBlank = {<br />&nbsp; length() == 0 || every { Character.isWhitespace(it.charAt(0)) }<br />}<br /><br /># Ruby (from Rails)<br />class String <br />&nbsp; def blank? <br />&nbsp;&nbsp;&nbsp; empty? || strip.empty? <br />&nbsp; end <br />end <br /><br />// Scala<br />class CharWrapper(ch: Char) {<br />&nbsp; def isWhitespace = Character.isWhitespace(ch)<br />}<br />implicit def charWrapper(ch: Character) = new CharWrapper(ch)<br />class BlankWrapper(s: String) {<br />&nbsp; def isBlank = s.isEmpty || s.forall(ch =&amp;gt; ch.isWhitespace)<br />}<br />implicit def stringWrapper(s: String) = new BlankWrapper(s)</code></div></pre><h3>Roll-your-own constructs</h3>
<p>In Java, you have the language and the libraries. The two are clearly distinct: you can write new libraries, but you cannot add language features.</p>
<p>In Java.next, the line between language and libraries is blurry. You can create new constructs that work like core language features. For example, Clojure provides an <code>and</code> function.</p>
<pre><div class="codeblock"><code>; clojure<br />(and 1 2) =&amp;gt; 2</code></div></pre><p>But maybe your problem domain isn't so binary. You need a <code>most</code> function, that returns true if most of its arguments evaluate to true. Clojure doesn't have this, but you can write one:</p>
<pre><div class="codeblock"><code>; clojure<br />(most 1 2) =&amp;gt; true<br />(most 1 2 nil) =&amp;gt; true<br />(most 1 nil nil) =&amp;gt; false</code></div></pre><p>The point here is not "Does my language need a 'most' conditional?" Probably not. The point is that different domains have different needs. In Java.next, the boundary between the language and the libraries is a minimized. You can adapt the language to your domain, instead of the other way around.</p>
<p>As another example, consider Ruby's attribute syntax:</p>
<pre><div class="codeblock"><code># Ruby<br />class Account<br />&nbsp; attr_accessor :name<br />&nbsp; dsl_attribute :type<br />end</code></div></pre><p><code>attr_accessor</code> is built into the language. <code>dsl_attribute</code> is a library method that I wrote, which allows you to omit the "=" when assigning values, e.g.</p>
<pre><div class="codeblock"><code># normal attributes<br />account.name = &quot;foo&quot;<br /><br /># equals-free attributes<br />account.type checking</code></div></pre><h3>Conclusions</h3>
<p>The Java.next languages share a ton of common ground.  Although I've used small isolated examples for explanation, the real power comes from using these features together.  Combining all the Java.next features leads to an entirely different style of coding.</p>
<ul>
<li>You do not have to code defensively, using a slew of factories, patterns, and dependency injection to keep your code testable and adaptable. Instead, you can build a minimal solution and evolve it.</li>
<li>Instead of coding in your Java.next language, you can develop internal Domain-Specific Languages (DSLs) that better match your problem domain.</li>
</ul>
<p>In my experience, this style of coding tends to reduce the size of a codebase by an order of magnitude, while <em>improving</em> readability.</p>
<p>Many people are looking for the "next big language." The next big language is already here, but it isn't a single language. It is the collection of ideas above (plus probably some I missed) as manifested in Java.next. </p>
<p>Does the transition to Java.next deserve the name "big"? Absolutely. In my experience, the move from Java to Java.next is every bit as big as the previous tectonic shifts in the industry, both in learning curve and in productivity advantages once you make the transition.</p>
<p>As an industry, we need to reset the bar to include Java.next. Once we have, we can have a conversation about the <em>differences</em> in these languages. I will take up the unique aspects of the Java.next languages in future installments of this series.</p>
<h3>Notes</h3>
<ul>
<li>This article is taken from the first half of the <a href="http://blog.thinkrelevance.com/2008/6/13/jvm-language-shootout-clojure-jruby-and-scala">JVM Language Shootout</a> talk that I wrote for <a href="http://www.nofluffjuststuff.com">NFJS</a>. Check the <a href="http://thinkrelevance.com/events">schedule</a> for a talk near you.</li>
<li>Suggestions for improving the code samples above are most welcome.</li>
<li>Thanks to Justin Gehtland, Jason Rudolph, Rob Sanheim, Glenn Vanderburg, and Greg Vaughn for reading an earlier draft of this article.</li>
</ul>
<h3>Footnotes</h3>
<ol>
<li>The <code>BigDecimal</code> example does not work as I would expect on the Scala build I have (2.7.1.final). But the important point is that I could make it work by adding an implicit conversion. I am not dependent on the language designers, I can improve the language myself.        </li>
</ol>
<h3>Revisions</h3>
<ul>
<li>2008/08/04: fixed errata, better Clojure example for expressive collections.</li>
<li>2008/08/12: added Rich Hickey's improved <code>blank?</code> example for Clojure.</li>
</ul>
<p>This article was originally published at <b><a href="http://blog.thinkrelevance.com/2008/8/4/java-next-common-ground">http://blog.thinkrelevance.com/2008/8/4/java-next-common-ground</a></b></p>
    ]]></content>
  </entry>
</feed>
