Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Builders, DSLs and Templates

Closure Delegates and Writing DSLs in Groovy

Build a readable domain-specific language in Groovy with closure delegates, resolve strategies, @DelegatesTo, command chains and operator overloading.

Groovy configuration files, Gradle build scripts and Jenkins pipelines look like a custom language, but they are ordinary Groovy. The trick is a handful of features: closures with a delegate, optional parentheses and semicolons, named arguments, and operator overloading. Once you understand them, you can build a small language for your own domain: deployments, orders, test data, rules.

Groovy cannot run on this site, so the Groovy code is read-only. The Java stand-ins reproduce the structure (a builder object receiving nested configuration) with lambdas.

The three things a closure knows

Every closure has three special properties:

  • this: the enclosing class where the closure was written.
  • owner: the enclosing object (a class, or another closure if nested).
  • delegate: an object you can set. By default it is the same as owner.

Method calls and property reads inside the closure are resolved through these. The order is controlled by the resolve strategy:

Strategy Order
OWNER_FIRST (default) owner, then delegate
DELEGATE_FIRST delegate, then owner
OWNER_ONLY / DELEGATE_ONLY one only
TO_SELF the closure itself

DSLs almost always use DELEGATE_FIRST or DELEGATE_ONLY.

A first DSL: configuring a server

GROOVY
class Server {
  String host = "localhost"
  int port = 80
  List routes = []

  void host(String h)  { this.host = h }
  void port(int p)     { this.port = p }
  void route(String path, String target) { routes << [path, target] }
}

static Server server(Closure body) {
  def s = new Server()
  body.delegate = s
  body.resolveStrategy = Closure.DELEGATE_FIRST
  body()
  s
}

def web = server {
  host "example.org"
  port 8080
  route "/", "index"
  route "/about", "about"
}

println web.host     // example.org
println web.routes   // [[/, index], [/about, about]]

Study what happens. The code block after server is a closure. server creates a Server, makes it the delegate, and calls the closure. Inside, host "example.org" has no host method in the script, so it is resolved against the delegate: Server.host(String). Parentheses are optional for a method call with arguments, which gives the declarative look.

Calling Closure.rehydrate

If you need a copy of a closure with a different delegate, use rehydrate(delegate, owner, thisObject). It is the thread-safe alternative to mutating the delegate on a shared closure.

@DelegatesTo: help for the IDE and the compiler

A closure is opaque to static tools. @DelegatesTo tells them what the delegate will be:

GROOVY
import groovy.transform.CompileStatic

@CompileStatic
static Server server(@DelegatesTo(Server) Closure body) {
  def s = new Server()
  def code = body.rehydrate(s, body.owner, body.thisObject)
  code.resolveStrategy = Closure.DELEGATE_FIRST
  code()
  s
}

With the annotation, IDEs offer completion inside the block and @CompileStatic checks that host and port exist. Use @DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = Server) to document the strategy too.

Nested blocks

Nested structure comes from nesting delegates:

GROOVY
class Deployment {
  String name
  List<Stage> stages = []

  void stage(String stageName, @DelegatesTo(Stage) Closure body) {
    def st = new Stage(name: stageName)
    body.delegate = st
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body()
    stages << st
  }
}

class Stage {
  String name
  List<String> commands = []
  void run(String cmd) { commands << cmd }
}

def d = new Deployment(name: "shop")
d.with {
  stage("build") { run "compile"; run "package" }
  stage("release") { run "upload" }
}
println d.stages*.commands   // [[compile, package], [upload]]

Here with is a GDK method that sets the delegate to the receiver and runs the closure. It is a ready-made mini builder.

Command chains

Groovy lets you drop dots and parentheses, so a chain of calls reads like a sentence:

GROOVY
pay 20 euros to bob
// means: pay(20).euros(to).bob   -- so design each step to return the next "word"

A command chain a b c d is parsed as a(b).c(d), and so on for longer chains, so pay 20 euros to bob becomes pay(20).euros(to).bob. Keep chains short, and make each step return an object that offers the next word. A common trick is to define words such as to as variables or small objects in the script binding.

Operator overloading for domain objects

Operators map to method names: + is plus, - is minus, * is multiply, << is leftShift, [] is getAt, == is equals, and <=> is compareTo. Add them to your classes and your DSL can say route1 << route2 or total = a + b. See operator overloading.

Other helpful syntax for DSLs:

  • Named arguments become a map: deploy host: "a", port: 22.
  • A trailing closure: retry(3) { ... }.
  • Number.metaClass or categories for units: 3.minutes.
  • Script bases: a custom BaseScript or GroovyShell with a CompilerConfiguration lets whole script files run with your DSL as their vocabulary and the imports already in place.

Design advice

  1. Write the usage first, then implement it.
  2. One word per concept. Avoid verbs that mean different things in different blocks.
  3. Fail with messages that name the DSL concept ("stage needs a name"), not the Java stack.
  4. Validate when the block ends, in one place.

Try it: a delegate-style builder in Java (stand-in)

A Java Consumer<Server> plays the closure, and the Server object is the delegate that receives the calls.

Java Stand-in: configuration DSL with a delegate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: nested blocks (stand-in)

Nesting is just a block inside a block, each receiving its own object.

Java Stand-in: nested deployment stages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does setting closure.delegate = obj allow?

    Unresolved method calls and property reads inside the closure can be forwarded to the delegate, depending on the resolve strategy.
  2. 2. Which resolve strategy do most DSLs use?

    DELEGATE_FIRST makes the DSL object win over names in the surrounding script.
  3. 3. What is @DelegatesTo for?

    The annotation documents the delegate for tooling, enabling completion and static type checks inside the block.
  4. 4. How is the command chain a b c d interpreted?

    Alternating names and arguments form a chain of method calls with the optional parentheses omitted.

Summary

  • A closure's delegate and resolveStrategy decide where unqualified calls go.
  • A DSL entry function creates an object, sets it as delegate with DELEGATE_FIRST, and runs the closure.
  • Nest blocks by nesting delegates; with is a built-in shortcut.
  • @DelegatesTo gives IDEs and @CompileStatic the delegate type.
  • Optional parentheses, command chains, named arguments and operator overloading make the syntax read naturally.

Next: Markup and JSON Builders