Saturday, September 22, 2007

Grokking Domain Specific Languages

A Domain Specific Language (DSL) is a programming language that is designed for a specific task. Although this definition is overly simplistic, it is good place to start.

As a Java developer I use domain specific languages in every non-trivial project that I am involved in. I use Hibernate, which uses an XML configuration file to map Java properties to data in a database. This XML file is a DSL. This also goes for DBUnit dataset files, Spring bean definitions, and even HTML. If might not be natural to think of a "configuration file" as a DSL, but it is.

For a really good discussion on DSL's and related concepts you should watch Language-oriented Programming and Language Workbenches, a presentation given by Neal Ford and Martin Fowler.

In watching the presentation I learned that DSL's don't always mean that you need to create a new language with a new syntax. Let me show you am example so that you can see what I mean.

The code below is a testing "language" of my own concoction that you would use in a JUnit test. It allows you to easily spin up a Spring config, prepopulate the database with DBUnit, then test the output of a Spring controller.


WebRequest req = createRequest()
.forURL("/app/login")
.usingPostMethod()
.withParams("user", "rhanson". "pass", "r@ckin")
.withSessionAttributes("user", null);

executeSpringController(
"loginController",
usingSpringConfig("applicationContext.xml"),
usingDBUnitData("dataset.xml"),
usingRequest(req)
)
.assertThatViewEquals("loginSuccess");
.assertThatSessionAttribute("user", isNotNull());
.assertThatSessionAttribute("user.name", equalTo("rhanson"));


I'll bet that without providing any documentation for the API that you can easily tell what the test is doing. In the presentation I noted, martin Fowler states that readability is one of the cornerstones of a DSL, and I think this one passes the test.

My DSL is written in Java, I didn't create my own programming language for my DSL. This is beneficial because it makes it easy for any Java developer to understand my DSL, and IDE's like Eclipse will be able to provide code completion, making it even easier to use.

DSL's make a lot of sense for simplifying tasks, in turn reducing the cost of a project.

Some references:

2 comments:

Anonymous said...

s/grep/grok/g ?

Robert Hanson said...

I am not sure why "grep" sounded right to me yesterday. Thanks for the note, I changed the title from Grepping to Grokking.