DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. A Basic Builder With Groovy

A Basic Builder With Groovy

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

Reinout Korbee user avatar by
Reinout Korbee
·
Jun. 13, 16 · Tutorial
Like (10)
Save
Tweet
Share
29.27K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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:

Company

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

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

Department

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();
    }
...

Employee

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') {
            name('John')
            role('Administrator')
        }
    }

    department('123') {
        employee('emp987') {
            name('Karen')
            role('Project Manager')
        }
    }

    department('456') {
        employee('emp456') {
            name('Mary')
            role('Developer')
        }
    }
}

CompanyBuilder Implementation

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

class CompanyBuilder extends BuilderSupport {

    @Override
    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
        company.getDepartments().add(department)
    } else if(current instanceof Department) {
        Department parentDep = (Department) current
        parentDep.getDepartments().add(department)
    }
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
        department.getEmployees().add(employee)
    }
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
        employee.setName(name)
    } else {
        throw new IllegalArgumentException("Invalid keyword 'name'")
    }
}

And:

Employee setEmployeeRole(String role) {
    if(current instanceof Employee) {
        Employee employee = (Employee) current
        employee.setRole(role)
    } 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:

Groovy

Groovy (programming language) Domain model

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Memory Debugging: A Deep Level of Insight
  • A Simple Union Between .NET Core and Python
  • Data Mesh vs. Data Fabric: A Tale of Two New Data Paradigms
  • PHP vs React

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: