Friday July 25, 2008
Idiomatic Groovy
The code shown in my screenshot yesterday was correct Groovy but not idiomatic Groovy. This was the method in question:
String setSearchString(searchString) {
def xml = proxy.GetSpeech(searchString)
def XmlParser parser = new XmlParser()
def speech = parser.parseText (xml)
"PLAY: " + speech.PLAY.text() +
"\nSPEAKER:" + speech.SPEAKER.text() +
"\nTEXT:" + speech.text()
}
In Java, new lines need to be closed with a quote and contain the "+" character. In Groovy, although the above is perfectly acceptable, one can use triple-quotes for multi-lines. Even nicer, in this case, is to use GStrings (expressions declared inside double-quotes), together with Expandos (dynamic collections), instead:
String setSearchString(searchString) {
def xml = proxy.GetSpeech(searchString)
def XmlParser parser = new XmlParser()
def speech = parser.parseText (xml)
Expando result = new Expando()
result.play = "PLAY: ${speech.PLAY.text()}"
result.speaker = "SPEAKER: ${speech.SPEAKER.text()}"
result.text = "TEXT: ${speech.text()}"
result.all = "$result.play\n$result.speaker\n$result.text"
}
Much neater, more readable, and the result is the same as before. Plus, it could probably be improved even further.
Jul 25 2008, 09:57:08 AM PDT Permalink


