A small DSL
A DSL in Groovy is a builder with names that read like the problem. The pieces are already here: a closure for a block, the delegate for the names inside it, and @DelegatesTo so an IDE and a static compiler know what the block may call.
A plan of tasks
plan.groovy
class Task {
String name
int priority = 0
@SuppressWarnings('ConfusingMethodName')
void priority(int value) {
priority = value
}
}
class Plan {
List<Task> tasks = []
void task(String name, @DelegatesTo(Task) Closure body) {
def task = new Task(name: name)
body.delegate = task
body.resolveStrategy = Closure.DELEGATE_FIRST
body()
tasks << task
}
}
def plan = new Plan()
plan.task('write') {
priority 1
}
plan.task('test') {
priority 2
}
plan.tasks.sort { Task a, Task b -> a.priority <=> b.priority }.each { Task task ->
println "${task.priority}: ${task.name}"
}
groovy plan.groovy
1: write
2: test
plan.task('write') { priority 1 } is a method call with a closure, and priority 1 inside it is a call on the delegate. The @SuppressWarnings is deliberate: the field and the method share the name on purpose, because the DSL wants priority 1 and not setPriority 1, and CodeNarc reports the pair as confusing.
What @DelegatesTo adds
The annotation changes no behaviour: it tells the compiler and the IDE that the closure runs against a Task. With @TypeChecked on the method that calls the block, an unknown name inside the block becomes a compile error instead of a run-time one, which is the difference between a DSL and a pile of strings.
Growing the DSL
grow.groovy
class Task {
String name
int priority = 0
List<String> tags = []
@SuppressWarnings('ConfusingMethodName')
void priority(int value) {
priority = value
}
void tag(String value) {
tags << value
}
@Override
String toString() {
"${name} [${priority}] ${tags.join(',')}"
}
}
class Plan {
List<Task> tasks = []
void task(String name, @DelegatesTo(Task) Closure body) {
def task = new Task(name: name)
body.delegate = task
body.resolveStrategy = Closure.DELEGATE_FIRST
body()
tasks << task
}
}
def plan = new Plan()
plan.task('release') {
priority 1
tag 'ci'
tag 'docs'
}
println plan.tasks[0]
groovy grow.groovy
release [1] ci,docs
One method on Task is one word of the DSL, so the vocabulary grows without touching the caller. The explicit toString makes the printed task stable, which is what a test of a DSL asserts.
Related
- delegate and owner: the mechanism under the DSL.
- The Groovy DSL of the Gradle course: a real build script read as the DSL it is.
Article author: Arthur Isaev