本文介绍了Groovy:闭包或方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经习惯使用Closures,我可以代替常规方法,即使我不需要访问自由变量。所以,我将使用这个:

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}

..而不是这样:

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

这是不好的做法吗?

谢谢!

推荐答案

我只使用闭包,我需要它们,即我默认使用方法。我这样做是因为

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. 关闭自己

  2. li>
  3. 关闭委托


在运行时更改,并且一个闭包的委托也可以更改为任何对象。

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


  • .class文件是我只有零个证据支持一个声明,一个常规的方法比闭包更有效,但我有怀疑。至少,很多类可能会导致你耗尽PermGen的内存空间 - 这经常发生在我频繁,直到我把我的PermGen空间到大约200MB

  • 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.

这篇关于Groovy:闭包或方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:48