Design your own DSL with Groovy

http://www.infoq.com/presentations/Design-Your-Own-DSL-with-Groovy

This presentation is by Guillaume Laforge, one of the Groovy founders, who does quite an interesting presentation about how Groovy supports Domain Specific Languages.

In short he starts with a simple example of how the Groovyisms in the language such as method calls without the need for parenthesis, named params and maps and list param injection into method arguments make for readable DSLs, all without touching any of the fancy meta-programming functions provided.  Very impressive. Other Groovy features that we sometimes forget about are ranges and operator overloading which were demonstrated here and  improve readability.

Then he scratches the surface a little deeper showing an example of how to add methods to existing classes using the metaClass property.  He takes the Number class and dynamically adds a method that constructs an object representing a measure – 6.pills or 6.euros which call a method Dosage getPills() that you inject into Number. 

   1: Number.metaClass.getPills = {

   2:     return new Dosage( numOfPills: delegate );

   3: }

When combined with the previous readability of maps representing method args and parenthesis less method calls, it can lead to some readable code

   1:  take  1.pills

   2:   of: SomeDrug,

   3: after: 6.hours // Number.metaClass.getHours = { … }

take is defined as

   1: def take(Map m, Dosage d)

This is a great intro to metaClass object protocol for those who haven’t come across it in Groovy.

The last part of the presentation talks about Abstract Syntax Tree transformations and how you can inject syntax into the Groovy language using annotations.  He uses the example of the Spock testing framework and how the @Speck annotation injects behaviours that wouldn’t normally be allowed in Groovy or Java, such as method names which are “strings with spaces and question marks?” and other neat stuff.  He also talks about how its important to limit what your DSLs can do in the JVM if you are giving them off to

I think in summary Groovy is a great language for supporting DSLs and the presentation gives a valuable insight into some of the more advanced groovy features, a worthwhile watch.

Leave a Reply