Analytics

Monday, January 16, 2012

Groovy DSL - A Simple Example

Domain Specific Languages (DSLs) have become a valuable part of the Groovy idiom. DSLs are used in native Groovy builders, Grails and GORM, and testing frameworks. To a developer, DSLs are consumable and understandable, which makes implementation more fluid as compared to traditional programming. But how is a DSL implemented? How does it work behind the scenes? This article will demonstrate a simple DSL that can get a developer kick started on the basic concepts.

What is a DSL

DSL's are meant to target a particular type of problem. They are short expressive means of programming that fit well in a narrow context. For example with GORM, you can express hibernate mapping with a DSL rather than XML.
  static mapping = {
    table 'person'
    columns {
      name column:'name'
    }
  }  

Much of the theory for DSLs and the benefits they deliver are well documented. Refer to these sources as a starting point:

A Simple DSL Example in Groovy

The following example offers a simplified view of implementing an internal DSL. Frameworks have much more advanced methods of creating a DSL. However this example does highlight closure delegation and meta object protocol concepts that are essential to understanding the inner workings of a DSL.