Groovy Closures

Some of my team have been impressed with Groovy’s support for closures:

Here is a simple closure:

def time(String message, Closure body) {
  def start =
  def result =
  def finish =
  Duration duration = Duration.between(start, finish)"$message took $duration")

This would allow you to go from:

def value = complexDatabaseQuery(1, 2, 3)


def msg = "Complex query 1, 2, 3"
def value = time(msg, {complexDatabaseQuery(1, 2, 3)})

This provides a simple decorating wrapper that records the time that the database call took without making the code less readable.

This could be made more sophisticated using:

def warnSlow(String message, def max_duration_in_seconds = 5, Closure body) {
def start =
def result =
def finish =
Duration duration = Duration.between(start, finish)
if (duration.getSeconds() > max_duration_in_seconds) {
warn “$message is slow, it took $duration which is longer than the threshold of $max_duration_in_seconds”

This permits simple performance checks to be added to code with minimal disruption.

How Jenkinsfiles Really Work

I only recently encountered the Jenkinsfile format. Previously I had used the clunky Jenkins UI or the cleaner Circle CI options.

Some of my colleagues had described it as using a special Groovy declarative syntax. It is in fact simply Groovy code using some neat tricks.

Groovy allows a closure (what other languages may call a lambda) to be used as a function parameter:

def block(Closure closure) {


This can then be used as follows:

block( { print (‘hello’) } )

Groovy allows the closure to be moved outside the brackets as a code block:

block() {

print ‘hello’


Here I have started to use the groovy trick of dropping brackets. In fact you can also drop the leading brackets:

block {

print ‘hello’


This is beginning to look like the pipeline or stage steps from a Jenkinsfile.

You can even add parameters:

def wrap(marker, Closure closure{

println marker

println marker


// Which can be used as:

wrap (‘name’) {

// something …


Jenkinsfiles are code pretending to be config, with the added benefit of being able to become code again when needed.

Equivalent Ecosystems: Groovy vs Elixir

Given that a little over two years ago I was a C# developer I have had to learn the JVM way of doing things fairly rapidly. Java does has many ways of solving things but these are those that I am familiar with:

Here is a map between the Java world and the Elixir world


Gradle => Mix =>

JUnit => ExUnit

JavaDoc => ExDoc

Dropwizard (or web framework of choice) => Phoenix

Jooq => Ecto

Groovy equivalent of Nuget : Grape

Here is this documentation for the Groovy equivalent to Nuget.

This is a small sample:

@Grab(group=‘org.springframework’, module=‘spring-orm’, version=‘3.2.5.RELEASE’) import    org.springframework.jdbc.core.JdbcTemplate

Grape does not seem to go as far as Nuget’s allowing upgrades, but it does do the configuration in the source code.