Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 144 ]

Command chains


We already knew that Groovy allows us to leave out parentheses when calling
methods. Another neat trick introduced in Groovy 1.8 is the ability to leave out the
dot when we chain method calls. Using this feature, we can further improve the
readability of our DSLs by adding constructs that mimic natural language. Take the
following chained method calls:


deposit (100.00).currency(USD).to(savings)

By leaving out the parentheses on these calls and the intervening dots we can express
this chain as follows:


deposit 100.00 currency GBP to savings

Building this mini DSL is relatively straightforward. First we need an enum for
currencies, which we statically import. We also define two method calls, convert
and deposit:


enum Currency { USD, GBP, EUR }

class Account {
double balance
}

static def convert ( currency, amount) {
def result
switch (currency) {
case Currency.USD: result = amount
break
case Currency.GBP: result = amount * 1.3
break
case Currency.EUR: result = amount * 1.1
}
result
}

static def deposit (double amount) {
[
currency: { Currency currency ->
[to: { account ->
account.balance += convert( currency , amount )
}
]

}
]
}

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