groovy Closures Wrapping behavior around a closure with a method


There are frequent behavior patterns that can result in a lot of boilerplate code. By declaring a method that takes a Closure as a parameter, you can simplify your program. As an example, it is a common pattern to retrieve a database connection, start a transaction, do work, and then either commit the transaction, or rollback the connection (in case of error), then finally close the connection:

def withConnection( String url, String user, String pass, Closure closure) {
    Connection conn = null
    try {
        conn = DriverManager.getConnection( url, user, pass ) conn )
    } catch (Exception e) {
        log.error( "DB Action failed", e)
    } finally {

withConnection( DB_PATH, DB_USER, DB_PASS ) { Connection conn ->
    def statement = conn.createStatement()
    def results = statement.executeQuery( 'SELECT * FROM users' )
    // ... more processing ...