Domain Specific Languages with Groovy
May 8th, 2008In general a DSL, domain specific language, is a language built to attack a specific problem domain and the lexicon of that language matches the problem domain. Huh?! What?! Is that even English?! In a nutshell a DSL is a language that maps to a very specific problem and the keywords are ones the users/developers of that problem space are familiar with. For example you have the problem domain of interacting with Apple’s iPod. Instead of using a general purpose programming language like Java you could develop a DSL that attacks the specific problem of interacting with and iPod. You could have specific commands like play, load, fast-forward, etc. Doing this in Groovy is really simple with method pointers. An example method pointer would be:
say = System.out.&println
So lets setup the iPod interaction scenario and create a DSL around that. The first thing we need is a Song class to hold song information:
class Song {
def title
def artist
def album
static Song newSong(title, artist, album) {
new Song(title: title, artist: artist, album: album)
}
String toString() {
"${title} by ${artist} on ${album}"
}
}
Next we need an iPod class to hold that information:
class iPod {
def static songs = []
}
This now gives us a basis for creating a DSL. We could use the classes out of the box but they are not in the language the use would be used to. Let’s abstract the user away from the class model and create a DSL they would be familiar with. We will do this by setting up some method pointers:
create_song = Song.&newSong
say = System.out.&println
play = { iPod.songs.each{song -> say song} }
load = iPod.songs.&add
Now we can write a little DSL script for interacting with out iPod:
load(create_song("Blue Collar Love", "StarFlyer 59", "Silver"))
load(create_song("Chasing Cars", "Snow Patrol", "Eyes Open"))
play()
This is just a small example of what is possible. There could be other ways to accomplish the same thing but I like this way. With the
ExpandoMetaClass
and meta-class programming combined with method pointers you can create a really interesting DSL that can help users or developers of your application by abstracting away the hard stuff. You could also embed a scripting language into your application by using a DSL.
This is just another example of what makes Groovy so "Groovy"