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 ? (开发者_如何学JAVAin 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 ?
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
精彩评论