It is not the parser I fear

time to read 2 min | 365 words

Martin Fowler talks about the almost instinctive rejection of external DSLs because writing parsers is hard. I agree with Fowler on that writing a parser to deal with a fairly simple grammar is not a big task, certainly there isn't anything to recommend XML for the task over an textual parser.

The problem that I have with external DSL is actually different. It is not the actual parsing that I object to, it is the processing that needs to be done on the parse tree (or the XML DOM) in order to get to an interesting result that I dislike.

My own preference is to utilize an existing language to build an internal DSL. This allows me to build on top of all the existing facilities, without having to deal with all the work that is required to get from the parse tree to a usable output.

In the case of the example that Fowler uses for his book (the state machine outlined here), the use of an internal DSL allows me to go from the DSL script to a fully populated semantic model without any intermediate steps. I give up some syntactic flexibility in exchange of not worrying about all the details in the middle.

The benefit of that is huge, which is why I would almost always recommend going with an internal DSL over building an external one. Here is a simple example, a business rule DSL:

    when not customer.IsPreferred and order.Total > 1000

apply_discount_of 5.precent:
    when customer.IsPreferred and order.Total > 1000

I wrote the code to use this DSL as a bonus DSL for my DSL talk in DevTeach. It took half an hour to forty five minutes, and it was at 4 AM. I extended this DSL during the talk to support new concepts and to demonstrate how easy it is.

I got to that point by leaning heavily on the host language to provide as much facilities as I could.

In short, it is not the parsing that I fear, it is all the other work associated with it.