Digital Magpie

Ooh, ooh, look - shiny things!

Strawman Arguments and Coding Styles

So there’s this blog post over on the Best in Class blog that talks about ceremony in programming languages and compares Clojure with Java on this basis. While I’d agree with the basic premise of the article (that there is less ceremony in Clojure), I’m less keen on the way it’s presented: by way of a needlessly verbose strawman example.

To be fair the article does kind of admit that this is what is being done, but it’s still annoying. With this in mind let’s see how well we can do with the Java version of the code, relying on a better coding style and a couple of freely available libraries (one of the platforms much touted strengths).

For the original — 28 line — version of the code I’ll refer you to the original post (but warn you that it’s presented in that well known code storage format, PNG!). The same code rewritten in a smarter manner, but still using only the core Java libraries. This gets it down to 10 lines of code and also makes the intent of the code clearer. There’s still a fair amount of ceremony about this however: the multiple imports, and all of the class and static main method boilerplate.

1
2
3
4
5
6
7
8
9
10
11
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;

class Distinct {
  public static void main(String... args) {
    Set distinct = new HashSet(Arrays.asList(new String[] {
        "foo", "bar", "baz", "foo"
    }));
  }
}

Let’s see if we can’t do a little better with the addition of some open source libraries. Enter Google Collections, a really neat library that improves the collections API from the JDK. We’re now down to 7 lines of code, and 2 of those are just closing braces! In any reasonably size program the class and main statements disappear into the noise, so we’re really saying that we have 2 import statements and a single line of code. That’s not too different from the Clojure version all things considered.

1
2
3
4
5
6
7
8
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;

class Distinct {
  public static void main(String... args) {
    Set distinct = newHashSet("foo", "bar", "baz", "foo");
  }
}

It’s interesting to note that the second Java version weighs in at 10 lines of code, versus 8 for the equivalent clojure version; not much of a difference really. I think that the benefits of Clojure come from it’s functional style, macro system, and excellent concurrency support — not from the fact that you can save a few lines of code here and there.