Cool Groovy features 2 – closures

A closure is a block of code (i.e. a function). In Java, to define a block of code, you would have to write a method or a class, but in Groovy you can write a closure and assign it to a variable, or simply declare it inline, when you want to use it. You can write methods to accept closures, which means you can write powerful and flexible APIs far more easily than with Java. In Java, if you want callers to be able to pass objects in to your API,  you would typically find yourself using the strategy pattern to define an interface that the classes of those objects must implement. Even if the caller only needs to write a couple of lines of code, this means that you have to write an interface, and they have to write an entire class, just to contain that code. By contrast, with Groovy, you can just write a method that declares that it accepts a closure. I’ll give a very simple example. I work in eCommerce, so let’s use the example of an eCommerce platform that uses a class called PromotionManager to deal with the promotions on the website. When writing this class, you don’t know all of the ways the rest of the platform might like to interact with the promotions. You need to provide a very flexible way of accessing the promotions, whilst still hiding the implementation details. With Groovy you could write a method like forEachPromo that iterates over all promotions and invokes a closure on each one:

class PromotionManager {
    Set<String> promos = new HashSet<String>()

    def PromotionManager() {
        promos.add "10% off"
        promos.add "Buy one get one free"
        promos.add "Free delivery"
    }

    def forEachPromo(Closure c) {
        for (String s : promos) {
            c(s)
        }
    }
}

So, for example, if a caller wanted to print out each promotion, they could call your API with:

PromotionManager pm = new PromotionManager()
 pm.forEachPromo {promo -> println promo }

For more details about closures, check out:

http://groovy.codehaus.org/Closures+-+Informal+Guide

This entry was posted in Groovy and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

503,793 Spambots Blocked by Simple Comments

HTML tags are not allowed.