Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 7

[ 147 ]

In fact, I can claim to have come up with one of the patterns myself. In 1989, while
working for Glockenspiel on a Cross GUI class library for C++, I was struggling for
a way to accommodate multiple library implementations in a single class library
header file. I proposed a solution to the company's founder and C++ guru, John
Carolan. John immediately christened the pattern, the Cheshire Cat. The Bridge
pattern in the GOF book also quotes this name for the pattern.


Using Groovy builders


An important and powerful part of Groovy is its implementation of the builder
design pattern. We implement design patterns in Java via Java classes and interfaces.
The Groovy implementation of Builder goes beyond this by providing a mini DSL,
which appears to embed the building process right into the language.


This style of markup is known as GroovyMarkup, and the code looks more like a
customized markup script than a regular Groovy script. This is due to the clever
use of Groovy's Meta Object Protocol (MOP) and closures.


At first glance, Groovy's builders defy our understanding of how things should
work in an object-oriented language. We no longer seem to be creating objects and
invoking methods as we would expect. For this section, let's suspend our disbelief
and just enjoy the power that Groovy builders provide.


Here we will just try to understand how to use GroovyMarkup to build things. Later
on in the chapter, we will cover how the MOP works, and it will become clear what
tricks are being employed by the Groovy designers in order to give us a very neat
way of constructing complex objects.


The best way to illustrate the GroovyMarkup feature is by way of an example.
We'll start with something simple. Suppose that we need to export customer records
from our e-commerce package in such a way that they can be used to initialize the
customer database of a new CRM system that has been installed by us. The CRM
system accepts customer records formatted in XML with customer IDs, names, and
addresses. The XML required might look like this:


<customers>
<customer id='1001'>
<name firstName='Fred' surname='Flintstone' />
<address street='1 Rock Road' city='Bedrock' />
</customer>
<customer id='1002'>
<name firstName='Barney' surname='Rubble' />
<address street='2 Rock Road' city='Bedrock' />
</customer>
</customers>
Free download pdf