Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 91 ]

when: "we invoke a method that accepts a String and a Closure"
closureMethodString("Dolly") { name ->
println "Hello, $name"
}
then: "the Closure passed in was executed with the parameter"
"""Greet someone
Hello, Dolly""" == output()

This construct can be used in circumstances where we have a look-up code that
needs to be executed before we can have access to an object. Say we have customer
records that need to be retrieved from a database before we can use them:


def withCustomer (id, Closure c) {
def cust = getCustomerRecord(id)
c.call(cust)
}

withCustomer(12345) { customer ->
println "Found customer ${customer.name}"
}

We can write an updateCustomer method that saves the customer record after
the closure is invoked, and amend our locked method to implement transaction
isolation on the database, as follows:


class Customer {
String name
}
def locked (Closure c) {
println "Transaction lock"
c.call()
println "Transaction release"
}

def update (customer, Closure c) {
println "Customer name was ${customer.name}"
c.call(customer)
println "Customer name is now ${customer.name}"
}

def customer = new Customer(name: "Fred")
Free download pdf