Work in Progress

This section I will discuss how builders work and how you can create your own builder. Builders are based on the builder pattern from the GOF design pattern book. It provides a way to build your own DSL and represents a powerful concept in Groovy. Let me start by saying I am not an expert on the subject of Groovy and this is a good thing for the following reasons. I will take you through a step by step example from a novice point of view. Much of the Groovy documentation is very useful but you have to know a lot to get the most out of the pages. I am starting smae pages to learn more about the power of Groovy and share that undestanding to other novices like me. It is also my hope that this will encourage other novices to take up the challange and write their own pages.

 Things you need to know

Let me also add that here are many examples of creating builders in Groovy, so I will use those examples to keep this presentation short.

I find it easier to understand concrete examples so I will start by using a standard builder MarkupBuilder; so let us see it in use:

// create a builder, (note: this is not in one of the packages that are automatically imported

def builder = new groovy.xml.MarkupBuilder()  // construct a builder step(1)

// create a simple xml markup

builder.stocks {                              // step (2)
    stock(symbol: 'JAVA')                     // step (3-1)
    stock(symbol: 'MSFT')                     // step (3-2)
    stock(symbol: 'IBM' )

==== result output =====>
  <stock symbol='JAVA' />
  <stock symbol='MSFT' />
  <stock symbol='IBM' />

So what is going on here:

step(1) - we just create a MarkupBuilder and save in in the variable builder, pretty much standard Groovy

step(2) - we invoke the method stocks on builder

The first thing to note is that builder does not know the method stocks so in java for example the compiler will give an error. In a dynamic language, where these decisions are made at runtime, the builder will missing method exception.