groovy Closures Wrapping behavior around a closure with a method

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 )
        closure.call( conn )
        conn.commit()
    } catch (Exception e) {
        log.error( "DB Action failed", e)
        conn.rollback()
    } finally {
        conn?.close()
    }
}


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


Got any groovy Question?