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:
- Closure itself
- Closure owner
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…