Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Implementing a Rules DSL


[ 294 ]

}
anyOf {
condition {
false
}
condition {
true
}
}
}
assert result == true
}

Handling events – deferred execution

Running this particular DSL from the command line is not particularly useful.
In order to be useful, our rewards DSL will eventually need to be hooked into the
runtime of our broadband provider's backend applications. Rewards need to be
applied as the result of different events in these systems. Some rewards will be
applied at the point of consumption of the individual media. Other rewards will be
applied at purchase time, and others when significant account events occur, such as
upgrading from one plan to another.


Placing all of the rewards in a single DSL script means that they will all be executed
in sequence when we load and evaluate the script. We could decide to separate
the rewards into three script files, one for each type of event. On each event being
triggered in the application, we would load and execute the appropriate reward
script; for a consumption event, we load the onConsume script, and so on. This would
work, but considering the amount of loading and parsing required for each event, it
could become a drag on performance.


There is an alternative approach that will allow us to keep all of the rewards in a
single script and also allow us to load the full script only once. Earlier on in this
chapter, we talked about using closures as a singleton. This means, having a single
instance of a named closure when the user supplies the implementation. We can
partition the rewards script into three possible sections by using this pattern.


onConsume = {
reward {
...
}
...
}
onPurchase = {
reward {

http://www.ebook3000.com
Free download pdf