Groovy:如何在 HibernateCriteriaBuilder 中分解代码?

发布于 2024-12-08 13:30:04 字数 893 浏览 0 评论 0原文

我正在尝试在闭包中分解一些常规代码。

这是一个示例代码,说明了我想要执行的操作(请参阅 HibernateCriteriaBuilder) 基本代码:

def criteria  = Account.createCriteria()
def results = criteria  {
  if(A) {
    // full code section when A
  } 
  if(B) {
    // full code section when B
  }
  ...
  if(N) {
    // full code section when N
  }
}

现在我想提取方法中的条件块,以便能够在其他条件中使用它们。 这是我现在拥有的代码:

def criteria = Account.createCriteria()
def results = criteria  {
 a(criteria)
 b(criteria)
 ...
 n(criteria)
}
def a(criteria) { if(A) /* full code section when A */ }
def b(criteria) { if(B) /* full code section when B */ }
...
def n(criteria) { if(N) /* full code section when N */ }

是否有一种绝妙的方法可以避免在每个方法的参数中传递条件? (换句话说,有没有办法获取调用上下文?)

并且,要将其扩展到其他闭包,我应该如何从常规闭包中提取方法?

I'm trying to factorize some groovy code inside a closure.

Here is a sample code illustrating what I want to do (see HibernateCriteriaBuilder)
base code:

def criteria  = Account.createCriteria()
def results = criteria  {
  if(A) {
    // full code section when A
  } 
  if(B) {
    // full code section when B
  }
  ...
  if(N) {
    // full code section when N
  }
}

Now I want to extract condition block in method to be able to use them in other criteria.
Here is the code I have now:

def criteria = Account.createCriteria()
def results = criteria  {
 a(criteria)
 b(criteria)
 ...
 n(criteria)
}
def a(criteria) { if(A) /* full code section when A */ }
def b(criteria) { if(B) /* full code section when B */ }
...
def n(criteria) { if(N) /* full code section when N */ }

Is there a groovy way to avoid to pass the criteria in the argument of each method ? (in other word, is there a way to get the calling context ?)

And, to extend this to other closure, how should I extract method from groovy closure ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小伙你站住 2024-12-15 13:30:04

一种可能性是将您的 a、b、n 方法更改为闭包,然后在调用它们之前将其 delegate 属性设置为 criteria,例如,

def criteria = Account.createCriteria()

def results = criteria  {
   a.delegate = criteria
   a()
}

def a = { if(A) /* full code section when A */ }

这满足您避免需要的要求通过每个方法的参数中的标准,但说实话,我并没有真正看到这会实现什么。

我认为您在问题中发布的代码更加紧凑和可读

One possibility is to change your a, b, n methods to closures, then set their delegate property to criteria before invoking them, e.g.

def criteria = Account.createCriteria()

def results = criteria  {
   a.delegate = criteria
   a()
}

def a = { if(A) /* full code section when A */ }

This meets your requirement of avoiding the need to pass the criteria in the argument of each method, but to be honest, I don't really see what this achieves.

The code you posted in your question is more compact and readable, in my opinion

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文