Groovy:如何在 HibernateCriteriaBuilder 中分解代码?
我正在尝试在闭包中分解一些常规代码。
这是一个示例代码,说明了我想要执行的操作(请参阅 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种可能性是将您的 a、b、n 方法更改为闭包,然后在调用它们之前将其
delegate
属性设置为criteria
,例如,这满足您避免需要的要求通过每个方法的参数中的标准,但说实话,我并没有真正看到这会实现什么。
我认为您在问题中发布的代码更加紧凑和可读
One possibility is to change your a, b, n methods to closures, then set their
delegate
property tocriteria
before invoking them, e.g.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