Chapter 11
[ 281 ]
This outputs:
first block encountered
first nested encountered
second block encountered
second nested encountered
In the previous code snippet, we see two styles of declaring a
specification parameter:
block ("spec") {
}
block "spec", {
}
The first uses the Groovy "function call" style, passing the closure after the method
parentheses. The second uses a parameter list, where one of the parameters is the
inline closure. Which one you choose is a matter of personal preference and style.
Some developers have a preference for the latter style in their examples. My own
personal preference is for the former, for the simple reason that it is easier for non-
technical users to grasp the necessity for a (something) {} syntax rather than a
something, {} syntax.
Closures as singleton blocks
The previous DSL style allows us to implement logic in repeatable named blocks.
A DSL script of this style could be run just once or many times. For instance, the
DSL could describe a set of business rules to be executed every time we encountered
a certain event. Sometimes we need a DSL to define logic that is only ever going to
be run once, or that needs to be stored and executed at will at some later date. In
this case, it may be better to limit the user to a single block instance, by having them
define the closure directly.
setup = {
println "Initialized"
}
teardown = {
println "finished"
}