Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 125 ]

Or we can use the follow method to follow the tweets of any user who posts about
the search terms that we are interested in:


// Follow users that have tweeted recently about Groovy and DSL
search ("Groovy DSL") { from, tweet ->
follow(from)
println "Following ${from}"
}

Adding all of these methods together is the first step towards writing a useful and
simple DSL for Twitter, but it suffers from a number of problems, which we need
to address.


Removing the boilerplate


Any DSL that we develop with Groovy is referred to as an embedded DSL. In other
words, it uses language features from the host language in order to build a new
mini dialect that achieves a particular goal. As programmers, we can appreciate the
elegance of how a closure can define a mini dialect that is embedded within our
code. We are used to all of the boilerplate that goes with using a Java library.


By boilerplate, we mean all of the setup code that is needed to establish the context
in which our code is running. This could be connecting to a database, establishing a
connection to a remote EJB object via a JNDI lookup, and so on. It also includes all
of the other code, which is superfluous to the problem at hand but is imposed by
the languages and environments that we use. The requirement in Java to write all
of our code within a class is a case in point. Comparing the Groovy "Hello, World"
program with its Java equivalents, we can see that all but a single line of the code is
boilerplate, imposed by the language:


// Groovy
println "Hello, World!"

// Java
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Free download pdf