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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Beyond Principles: Embracing Heuristics in DDD for Practical Solutions
  • 10 Things to Avoid in Domain-Driven Design (DDD)
  • Why and How To Integrate Elastic APM in Apache JMeter
  • CRUDing NoSQL Data With Quarkus, Part Two: Elasticsearch

Trending

  • System Coexistence: Bridging Legacy and Modern Architecture
  • Introduction to Retrieval Augmented Generation (RAG)
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  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.

By 
Reinout Korbee user avatar
Reinout Korbee
·
Updated Jun. 13, 16 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
31.6K 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.

Related

  • Beyond Principles: Embracing Heuristics in DDD for Practical Solutions
  • 10 Things to Avoid in Domain-Driven Design (DDD)
  • Why and How To Integrate Elastic APM in Apache JMeter
  • CRUDing NoSQL Data With Quarkus, Part Two: Elasticsearch

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!