Archive

Archive for the ‘Clojure’ Category

How Clojure improved my Groovy

January 15, 2010 7 comments

Dave Thomas and Andy Hunt have been saying for years that you should learn new programming languages. Doing so improves your skill in any language, whether you use the new language or not. I believed this with some skepticism, but decided nonetheless to start learning Clojure after reading The Pragmatic Programmer.

I’m reading and working through Programming Clojure, and one of the examples in the book looked like this:

(use '[clojure.contrib.str-utils :only (str-join)])
(str-join "-" ["hello", "clojure"])

Then, a week or so later, as I was working on some Groovy code, I saw something like the following:

def elements = ["It", "works", "on", "my", "machine!"]

def sb = new StringBuilder()
elements.eachWithIndex { element, index ->
  if (index == 0) {
    sb.append(element)
  } else {
    sb.append(" ")
    sb.append(element)
  }
}

assert sb.toString() == "It works on my machine!"

And I thought, “man, this code would be so much better in Clojure!” Since I can’t use Clojure for my job (yet), I set out to find a better way to do this in Groovy. I decided to look for something similar to Clojure’s str-join for Groovy, and I found the join() method. It does exactly what I needed!

def elements = ["It", "works", "on", "my", "machine!"]

def sb = new StringBuilder()
sb.append(elements.join(" "))

assert sb.toString() == "It works on my machine!"

And so, I discovered for myself that Dave and Andy were right. Knowing Clojure (specifically, the clojure-contrib library) helped me to write better Groovy code.