I was recently talking about what I call micro DSLs and I thought I’d follow up with another example.
So, another example of a micro DSL I found myself writing is one of finding some object within a collection of differently typed objects. In my example, I want to find a
Race object inside a bunch of calendar events objects, the finder micro DSL looks like this.
The way the class is built, it forces the client to use it such.
Where find is statically imported and race and events have been pre-populated.
The original version had a method in the class to do the find, in the context of this class it was harder to test the find. I had a bunch of mocks and I was testing the find function amongst other behaviours of the class. The search line looked something like this.
What’s with “micro DSL”?
Why I term this a micro DSL is that it has a very specific usage (to find a race within a calendar) and it has a private constructor and public static creation method to ensure strict usage. The real thing though is the method names don’t really do what they imply they’re going to do. The
in method actually does the search, but the
find method doesn’t do any such thing; it creates an object.
Micro DSLs are recognisable by their tiny-domain, the way in which construction is done to ensure methods can only be called in a certain order that makes sense to the domain and badly named methods.
How do you feel about this? When its used in a tiny domain like this and when it expresses the conversation more concisely than the alternatives, I feel pretty good about it. It makes me realise its not the words (method names) that are important, its the sentences they put together. So I’m compromising on realistic method names for more expressive sentences. The fact that the class prevents you from constructing invalid sentences just makes the warm feeling grow.
- Domain Specific Languages (Addison-Wesley Signature), Martin Fowler
- DSLs in Action, DSLs in Action
- The Definitive ANTLR 4 Reference: Building Domain-Specific Languages (Pragmatic Programmers), Terence Parr