DevOps / Apache Groovy Interview questions
Which is better for a DSL: Groovy closures or a builder class, and why?
This isn't strictly either-or in practice - Groovy's own built-in builders, like MarkupBuilder, are themselves implemented using closures under the hood, so the more useful framing is which layer of abstraction to expose to the DSL's actual end users.
Raw closures with delegate reassignment give maximum flexibility with the least code to write upfront - fine for a simple, internal DSL where the audience is other developers comfortable reading Groovy closure syntax directly and the structure being configured is relatively simple and stable.
A dedicated builder class, potentially still implemented internally using closures and delegation, is worth the extra upfront work when the DSL needs a more constrained, discoverable API - IDE autocompletion working well, clear validation errors, and a documented set of exactly what's configurable - which matters more as the DSL's audience grows beyond the original author or the structure becomes more complex.
In short: reach for closures directly for something quick, internal, and structurally simple; invest in a purpose-built builder class when the DSL will be used broadly, needs strong tooling support, or benefits from validating its structure rather than accepting arbitrary closure content.
More Related questions...