A Basic Builder With Groovy

DZone 's Guide to

A Basic Builder With Groovy

This article shows how to create a basic Builder using the Groovy Builder syntax.

· Java Zone ·
Free Resource


A builder, in its most simple form, can be thought of as a hierarchically nested constructor which may take a closure as argument. Within the closure, further constructors may be called.

You, as implementer of a builder, decide what the constructors do, how they're called and which arguments they take. Normally, you will already have an existing data structure that you would like to construct or modify with builder syntax. These data structures are, for example, an XML document, a Swing UI or a JSON document. In these cases, Groovy provides builders out-of-the-box. Maybe you have a domain model, or a very specific document or message type that you would like to create and you want something more specialized. You need a domain specific language and the Groovy Builder syntax is just what you're looking for. I recently developed a builder for meta-data structures encoded in the Statistical Data and Metadata Exchange (SDMX) format.

But let's not get lost in detail and start with a simple example. Here, we'll create a builder for a domain model consisting of a Company with Departments and Employees. A Department may have zero or more Departments. Each object has an ID that is passed through the constructor.

As usual when developing domain specific languages, I start with a domain model (if it doesn't already exist), make a design of the language and then finally I implement the syntax.

Domain Model

The domain model is as follows:


public class Company {
    private List departments;
    private final String id;

    public Company(String id) {
        this.id = id;
        this.departments = new ArrayList();


public class Department {
    private List employees;
    private List departments;
    private final String id;

    public Department(String id) {
        this.id = id;
        this.employees = new ArrayList();
        this.departments = new ArrayList();


public class Employee {
    private String name;
    private String role;
    private final String id;

        public Employee(String id) {
        this.id = id;

CompanyBuilder syntax

The CompanyBuilder syntax will look as follows:

CompanyBuilder builder = new CompanyBuilder()

Company company = builder.company('ABC') {
    department('XYZ') {
        employee('emp12345') {

    department('123') {
        employee('emp987') {
            role('Project Manager')

    department('456') {
        employee('emp456') {

CompanyBuilder Implementation

A builder extends the BuilderSupport class. At least one of the createNode() methods must be implemented:

class CompanyBuilder extends BuilderSupport {

    protected Object createNode(Object name, Object id) {
        switch(name) {
            case 'company': return createCompany(id)
            case 'department': return createDepartment(id)
            case 'employee': return createEmployee(id)
            case 'name': return setEmployeeName(id)
            case 'role': return setEmployeeRole(id)
            default: throw new IllegalArgumentException("Invalid keyword $name")

Each keyword delegates to a method that returns the requested object:

Company createCompany(String id) {
    Company company = new Company(id)
    return company

The Company is a very simple object to create. The Department however, needs either a relation to a Company or another Department:

Department createDepartment(String id) {
    Department department = new Department(id)
    if(current instanceof Company) {
        Company company = (Company) current
    } else if(current instanceof Department) {
        Department parentDep = (Department) current
return department

The variable 'current' references the current object. If you are in the scope of a closure this is the object that is returned by the constructor. In our case, this is either a Company object or a Department object.

The Employee only has a reference to a Department:

Employee createEmployee(String id) {
    Employee employee = new Employee(id)
    if(current instanceof Department) {
        Department department = (Department) current
return employee

The Employee has two attributes: name and role. Here, I choose to set them through a constructor. It is also possible to use a map with named parameters, but that doesn't scale. The implementation is the same, but here error handling is added to make sure that the name and role keywords are used in the right context:

Employee setEmployeeName(String name) {
    if(current instanceof Employee) {
        Employee employee = (Employee) current
    } else {
        throw new IllegalArgumentException("Invalid keyword 'name'")


Employee setEmployeeRole(String role) {
    if(current instanceof Employee) {
        Employee employee = (Employee) current
    } else {
        throw new IllegalArgumentException("Invalid keyword 'role'")

Unit Tests

Just so that you believe me, here is a unit test:

assert company != null && company.id == 'ABC'
assert company.departments.size() == 2

Department dept1 = (Department)company.departments[0] 
Department dept2 = (Department)company.departments[1]

assert dept1.id == 'XYZ' 
assert dept2.id == '123'

assert dept1.departments.size() == 0
assert dept2.departments.size() == 1

Department dept3 = (Department)dept2.departments[0]

assert dept1.employees.size() == 1
assert dept2.employees.size() == 1
assert dept3.employees.size() == 1

Employee emp1 = (Employee) dept1.employees[0]
Employee emp2 = (Employee) dept2.employees[0]
Employee emp3 = (Employee) dept3.employees[0]

assert emp1.name == 'John' && emp1.role == 'Administrator'
assert emp2.name == 'Karen' && emp2.role == 'Project Manager'
assert emp3.name == 'Mary' && emp3.role == 'Developer'

Now you've got a builder that can create hierarchical structures and set attributes on each element. The code can be downloaded from GitHub: GroovyBuilder.

Related Refcard:

builder, domain specific language, groovy

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}