Simple Groovy example demonstrating how you can use Closures to refactor code.

Groovy Closure example

I had a data structure similar to the zones variable declared in the getZone method of this script.

Basically, it’s a List. Each entry has an embedded map. And the countries entry in the Map contains a nested List.

The final twist is that the zone b entry has a map entry for countries, adding another intermediary level.

Now I simplified the code in this example to just hold one piece of information on a Country and print the name of the country.

So you will see this repeats when I process zones 1 to 9 one way then zone b, which contains bases with countries embedded within.

So in order to refactor out the code duplication, I created a closure called processCountry that does exactly what the old embedded code does.

Now my couple of ‘each’ methods can both call the closure which I like to think of as a named reference to a block of code. (A function pointer for you C guys).

Now the c variable which is to the left of the rocket symbol ‘->’ in the closure is like an entry parameter, so when I used the named closure, I can either use parentheses or drop them.

I’ve shown both syntaxes. The first is the Groovier way, less ceremony, the latter is the Java syntax centric.

Now you can easily imagine how processCountry could easily expand to five or ten lines or repeated code. Refactoring out cut/paste style of coding.

Now you might say. What the heck processCountry looks like a subroutine or method in Java speak.

But the beauty with Groovy is you could dynamically modify processCountry at runtime, and point it to some other block of code without resorting to the complexities of reflection or AOP (Aspect Orientated Programming – a proxy wrapper if you will).

Enjoy.

Associated link others may find useful:

  • Groovy Closures tutorial
  • I’ve since posted a more in depth article based on this post, highlighting the savings in lines of code more effectively here.
Advertisements

About this entry