44

Groovy Closures

 4 years ago
source link: https://www.tuicool.com/articles/v2eaaaa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK