Groovy, Java, Programming, Scripting

A Groovy Dice Roller DSL Solution

I’ve been looking at Ruby Quiz 61 for a while and I decided to take a look at solving it in Groovy as well.

Here’s a rough draft of what a solution might look like. So what did I learn about doing DSL in Groovy?

Well overall I think the Ruby solution is probably more elegant but Groovy’s Categories make meta-programming easy for meta village idiots like myself. I really struggled at first though because the documentation is so poor. I had to refer to Groovy in Action to sort myself out.

The key issue was that a category must consist of static methods which have at least one parameter, the first parameter should be of the type you want to “attach” the method to (so in this example I want to add the method d to Integer). You then effectively form a closure on the block of code to be executed with the method use which takes a list of categories you want to have active in the block.

The Eval object acts as a kind of synonym for GroovyShell but is meant to remove the boilerplate. Eval.me invokes the block with no pass-in parameters.

I think that Groovy does a decent job of providing solutions to problems like this but if you had a choice to make would you choose JRuby or Groovy? It ain’t easy. What I am convinced off is that both should be part of the library mix in any Java shop that is looking to the future.

Standard