Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 142 ]

These features combine neatly together for use in a DSL. Consider a method call
to transfer funds from one account to another for a customer. The conventional
way to lay out parameters to a method is in the order of their importance from a
programming logic point of view. So we declare the customer parameter as the first
parameter, as this is the primary object that we are operating on. We follow this with
the accounts we are operating on, and finish up with the amount to transfer:


def transfer( customer, from_account, to_account, amount) {
println """debiting ${amount} from ${from_account} account,
crediting ${to_account} account for ${customer}"""
}
transfer("Joe Bloggs", "checking", "savings", 100.00)

Reading the method call does not provide any immediate clarity as to the function
of all of the parameters. So we will only know for sure that savings is the receiving
account by checking the method documentation to see that the third parameter is the
receiving account. What if we make a small change to this method and have it accept
named parameters instead?


def transfer( transaction, amount) {
println """debiting ${amount} from ${transaction.from} account,
crediting ${transaction.to} for ${transaction.for}"""
}

transfer 100.00, from: "checking", to: "savings", for: "Joe Bloggs"
transfer for: "Joe Bloggs", 200.00, from: "checking", to: "savings"

Now our method call is starting to look like English. We also have a good degree
of flexibility over the order in which we place the named parameters and where we
place the amount parameter, so if we like, we can turn the call into something that
looks like English:


transfer 100.00, from: "checking", to: "savings", for: "Joe Bloggs"

Named parameters in DSLs


Being able to clarify exactly what a parameter means is a very useful technique to use
in a DSL. Not only does it improve the readability of the DSL, but it can also remove
potential ambiguities. Looking back at our GeeTwitter DSL from the last chapter,
we had a sendMessage call, which sends a text message to a Twitter user. Both the
message parameter and the user id parameter were defined as strings, which of
course could lead to ambiguity in the calling sequence:


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