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.

Comments:

How about this?

["PLAY: ${speech.PLAY.text()}\\n",
"SPEAKER: ${speech.SPEAKER.text()}\\n",
"TEXT: ${speech.text()}"].sum("")

or if you do this a lot try this:

class AddLines
{
def val
def plus(obj){new AddLines("val":(val ? "$val\\n$obj" : obj))}
String toString(){ val }
}

["PLAY: ${speech.PLAY.text()}",
"SPEAKER: ${speech.SPEAKER.text()}",
"TEXT: ${speech.text()}"].sum(new AddLines())

Posted by Dale Frye on July 25, 2008 at 08:00 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
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
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today