Groovy Execute Around Pattern

In my previous post, we saw how languages with higher order functions make the implementation of Command Pattern very trivial. With a slight modification, we can achieve the Execute Around pattern.

Suppose we have two types of transactions (atomic operations). Let's represent them using closures transactionOne and transactionTwo respectively. Now we want want to perform a set of operations before these running these transactions as well as another set of operations after running the transactions. Essentially, we are trying to avoid duplicating the logic to be run before and after the transactions.

Since closures are higher-order, we can create a common function and pass the transaction to be run as an argument. This function can house the common code to be executed and the transaction can be performed by invoking the passed closure.

You may take a look at my post on higher order functions, if you are not already familiar with the concept

The below code shows all these in action.

def transactionOne = {
    println "Executing transaction-1"
}

def transactionTwo = {
    println "Executing transaction-2"
}

def executeInTransactionBoundary(def transaction) {
    println "Starting a transaction context"
    transaction()
    println "Finalising the transaction"
}

executeInTransactionBoundary(transactionOne)
executeInTransactionBoundary(transactionTwo)

The code will produce the following output.

Starting a transaction context
Executing transaction-1
Finalising the transaction
Starting a transaction context
Executing transaction-2
Finalising the transaction

Again, the higher-order function feature of the language is helping us to implement the Execute Around pattern in a concise way.