Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 10

[ 263 ]

Ideally, we want to be able to describe our data in a declarative style. The syntax
of the data definition should match the structure of the resulting data as closely
as possible. This is an ideal situation in which to use a builder to take care of
construction. With a builder, it should be possible to create a declarative markup
style script for building datasets. The builder can take care of the complexities
of construction.


Let's first of all imagine how a builder for customers may look in use. We probably
want to handle multiple customers, so a top-level customers method is useful.
We could have multiple customer blocks nested in the following code. Nesting is a
good way of depicting ownership in a one-to-many relationship, so our Customers
markup would probably look something like the following:


builder.customers {
customer{
invoice {
salesOrder()
salesOrder()
salesOrder()
}
}
}

We need to be able to set the fields for each entity as it is created. We could have a
pretended method for each field as follows:


builder.customers {
customer {
firstName("Fred")
lastName("Flintstone")
invoice {
salesOrder {
sku("productid01")
amount(1)
price(1.00)
}
salesOrder {
sku("productid02")
amount(2)
price(1.00)
}
salesOrder {
sku("productid03")
Free download pdf