Alex Rivera | Logout

Groovy : Closures or Methods

Asked 2009-12-01T10:55:11.047
40

I've got into the habit of using Closures everywhere I can in place of regular methods, even when I don't need access to free variables. So, I will use this:

def addNumbers = { left, right -> left + right }

.. instead of this:

def addNumbers (left,right) { left + right }

Is this bad practice? I far prefer the extra power I get when using closures over methods, and I far prefer the syntax.

Thanks!

Edit
Report

1 Answer

7

While all the things @Don says are true, I don't know that any of them are all that significant. You can override the delegate of a closure which can change execution, but unless you're passing the closure around (which you can't do with a method anyways) you don't really have to worry about any of those things happening. Playing with the delegate is a feature, not a liability.

As for a possible performance hit from extra class files, why are you using Groovy if you're that worried about performance?

My opinion is that it doesn't really matter. If you have a lot of people on your team that are old Java developers, they're probably going to dislike it when you use closures where a method will do. On the other hand, someone fluent in Groovy will get annoyed if you clutter everything up with methods when a closure makes more sense.

tl;dr - There is no hard and fast rule, instead you should exercise good judgement with an eye towards code readability.

answered 2009-12-28T21:16:18.017

Your Answer