Defining data structures as code in Groovy
An important and powerful part of Groovy is its implementation of the Builder pattern. This pattern was made famous by the seminal work Design Patterns: Elements of Reusable Object-Oriented Software; Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
With builders, data can be defined in a semi-declarative way. Builders are appropriate for the generation of XML, definition of UI components, and anything that is involved with simplifying the construction of object graphs. Consider:
Teacher t = new Teacher('Steve') Student s1 = new Student('John') Student s2 = new Student('Richard') t.addStudent(s1) t.addStudent(s2)
There are a few issues with the previous code; verbosity and the lack of a hierarchical relationship between objects. This is what we can do with a Builder in Groovy:
teacher ('Jones') { student ('Bob') student ('Sue') }
Out of the box, Groovy includes a suite of builders for most of the common construction tasks that we might...