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 = Instant.now()
  def result = body.call()
  def finish = Instant.now()
  Duration duration = Duration.between(start, finish)
  log.info("$message took $duration")
  result
}

This would allow you to go from:

def value = complexDatabaseQuery(1, 2, 3)

to

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 = Instant.now()
def result = body.call()
def finish = Instant.now()
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”
}
result
}

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s