Friday Jul 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.

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« July 2008 »
SunMonTueWedThuFriSat
  
4
5
6
11
12
13
14
17
26
30
  
       
Today