Archive
How Clojure improved my Groovy
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.
SnakeYAML and Groovy
I had some fun playing with SnakeYAML and Groovy the other day. Below are some of my results. If you want to run this in your groovyConsole, you need to download SnakeYAML and add the snakeyaml-<version>.jar to your classpath.
From YAML to Groovy:
import org.yaml.snakeyaml.Yaml
Yaml yaml = new Yaml()
def obj = yaml.load("""
a: 1
b: 2
c:
- aaa
- bbb""")
assert obj.a == 1
assert obj.b == 2
assert obj.c == ["aaa", "bbb"]
From Groovy to YAML:
import org.yaml.snakeyaml.Yaml def map = [name: "Pushkin", aliases: ['P', 'Push']] Yaml yaml = new Yaml() String output = yaml.dump(map) assert output == '''name: Pushkin aliases: [P, Push] '''
Isn’t YAML so much simpler and cleaner than XML? Why aren’t more of us using YAML with Java and Groovy?
Recent Comments