de.velopmind | The Det about Programming

June 25, 2008

An little pattern trap

Filed under: Groovy, Style — de.velopmind @ 7:24 am

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?


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: