Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

question from:https://stackoverflow.com/questions/1825424/groovy-closures-or-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

I only use closures where I need them, i.e. I use methods by default. I do this because

  • Methods are simpler than closures. Closures have a delegate, an owner, retain access to variables that were in their local scope when created (what you call "free variables"). By default method calls within a closure are resolved by:

    1. Closure itself
    2. Closure owner
    3. Closure delegate

But this order can be changed at runtime, and a closure's delegate can also be changed to any object.

All of these factors combined can make some code that uses closures very tricky to grok, so if you don't need any of this complexity I prefer to eliminate it by using a method instead

  • A .class file is generated for each closure defined in Groovy. I have exactly zero evidence to support a claim that a regular method is more performant than a closure, but I have suspicions. At the very least, a lot of classes may cause you to run out of PermGen memory space - this used to happen to me frequently until I raised my PermGen space to about 200MB

I have no idea whether the practice I'm advocating (use methods by default and closures only when you need them) is widely considered a "best practice", so I'm curious to hear what others think.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...