Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 11

[ 291 ]

Ideally, we want to have a single condition in each block, so we need to allow
multiple blocks, and provide an easy way to describe inclusive and exclusive
sets of conditions. Adding two more closures to the DSL gives us just that.


reward ( "anyOf and allOf blocks" ) {
allOf {
condition {
}
... more conditions
}
condition {
}
anyOf {
condition {
}
+... more conditions
}
grant {
}
}

Now we can have multiple condition blocks within a reward. All condition blocks
must be true for the reward to be granted. The allOf and anyof condition blocks
can each themselves contain multiple condition blocks. For an allOf condition block
to be true, all child conditions must be true. For an anyOf block to be true, at least
one of the child conditions must be true.


To implement this scheme, we need to tell the condition block whether it should
AND (&&) or OR (||) its result to the current condition of the expression. We shall
store the current status of the condition in a binding variable called result and
decide whether to && or || based on the status of the binding Boolean useAnd. To
begin with, for each reward we presume that the reward is passed, and set result
to true. We set the default operator to && by setting useAnd to true.


binding.reward = { spec, closure ->
closure.delegate = delegate
binding.result = true
binding.useAnd = true
closure()
}

binding.condition = { closure ->
closure.delegate = delegate
Free download pdf