The Det about Programming

Just another progger’s blog

An little pattern trap

A little trap I recognised to fall in quite often in Grooy is about GStrings.

Groovy has a special String syntax which allows to put in variable parts, making it a simple form of templates.

So you can work for example with a variable ‘name’ this way:

def names = ["Zaphod", "Ford", "Trillian"]
names.each { name ->
    println "The name is: $name"
}

In the String printed out the variable $name is replaced by the current value of the parameter ‘name’ of the iteration.

That technique makes it also quite convenient to generate some html :

names.each { name ->
    println """<font color="red">$name</font>"""
}

This pattern to write out a variable wrapped in additional text in a GString is so common, that I often enough forget that a variable can be printed out directly and so find myself writing such lines:

println "$someSting"

(Some people considered me being a formalist when they read such code of mine, trying to develop patterns as generic as possible and applying them in every and all cases.
Well, I’m not! It’s simply too less active thinking, too much reflex ;-) )

Do you know of other patterns often applied too mechanically?

June 25, 2008 Posted by thedetdev | Groovy, Style | | No Comments Yet