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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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).

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

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 }}