Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MetaBuilder: a builder for builders

DZone's Guide to

MetaBuilder: a builder for builders

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

The title says it all, MetaBuilder is a builder that let's you create other builders. Dave Masser-Fryehas released this project under the Apache Software License 2.0 at sourceforge, here is the link to the project site. What makes MetaBuilder appart from using the standard Groovy options to make builders is that it follows an schema approach, in other words, you define which properties and the relationships between nodes as you go, in a similar manner as you define an object graph with XML.

Following the example from the documentation, NodeBuilder is a builder created with the standard way (extend BuilderSupport/FactoryBuilderSupport/GroovyObjectSupport or even ObjectGraphBuilder, the usual)

        def nb = new NodeBuilder()

def anInvoice = nb.invoice(date: new Date()) {
items {
item(upc: 123, qty: 1, price: 14.99)
item(upe: 234, qty: 4, price: 14.99)
item(upc: 345, qty: 6, price: 14.99)
}
}

There is a typo in one of the properties of the second item. the code will compile but will either throw an exception or ignore the property value. Either way you will have an incorrect result. Defining the schema with MetaBuilder is pretty straightforward

        import groovytools.builder.*

def mb = new MetaBuilder()
def invoiceSchema = mb.define {
invoice (factory: Invoice) {
properties {
date()
}
collections {
items {
item (factory: Item) {
properties {
upc()
price()
qty()
}
}
}
}
}
}

def anInvoice = mb.build {
invoice(date: new Date()) {
items {
item(upc: 123, qty: 1, price: 14.99)
item(upc: 234, qty: 4, price: 14.99)
item(upc: 345, qty: 6, price: 14.99)
}
}
}
assert(anInvoice instanceof Invoice)

Not only will this code create a graph but it will also use the correct classes for the invoice and item nodes (given that you have an Invoice and an Item class).

Using Containers? Read our Kubernetes Comparison eBook to learn the positives and negatives of Kubernetes, Mesos, Docker Swarm and EC2 Container Services.

Topics:

Published at DZone with permission of Andres Almiray. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}