Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Building a Builder


[ 264 ]

amount(3)
price(1.00)
}
}
}
}

This will work. However, it is not immediately clear to a reader of this script that
lastName is an object attribute and invoice is a new subsidiary object. A better option
is to set object attributes as mapped parameter values. The following script is far
clearer in its intent, so this is the one we will try to implement:


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", amount:3, price:1.00)
}
}
}

As it happens, the BuilderSupport hook methods and their calling sequence
work perfectly in step with the GORM APIs that we need in order to construct
our customer records:



  • The createNode method will be called in the correct top down sequence,
    allowing us to create the appropriate Customer, Invoice, or SalesOrder
    class as required

  • The setParent hook is called after both parent and child objects have
    been constructed, allowing us to call Customer.addToInvoices or
    Invoice.addToOrders when we need to

  • The nodeCompleted hook can be used to intercept when an object needs to
    be saved


The following code snippet contains a rudimentary builder class based on
BuilderSupport that constructs customer, invoice, and sales order objects through
GORM. The same style of builder could work equally well with whatever other
persistence method we choose:


class CustomersBuilder extends BuilderSupport {
def createNode(name){
Object result = null
switch (name) {
case "customer":

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