97 Things Every Programmer Should Know

(Chris Devlin) #1

(^46) 97 Things Every Programmer Should Know


Domain-Specific Languages ........................


Michael Hunger


WHENEVER YOU LiSTEN TO A DiSCUSSiON BY ExPERTS in any domain, be
it chess players, kindergarten teachers, or insurance agents, you’ll notice that
their vocabulary is quite different from everyday language. That’s part of what
domain-specific languages (DSLs) are about: a specific domain has a specialized
vocabulary to describe the things that are particular to that domain.


In the world of software, DSLs are about executable expressions in a language
specific to a domain, employing a limited vocabulary and grammar that is
readable, understandable, and—hopefully—writable by domain experts. DSLs
targeted at software developers or scientists have been around for a long time.
The Unix “little languages” found in configuration files and the languages cre-
ated with the power of LISP macros are some of the older examples.


DSLs are commonly classified as either internal or external:


Internal DSLs
Are written in a general-purpose programming language whose syntax
has been bent to look much more like natural language. This is easier for
languages that offer more syntactic sugar and formatting possibilities (e.g.,
Ruby and Scala) than it is for others that do not (e.g., Java). Most internal
DSLs wrap existing APIs, libraries, or business code and provide a wrap-
per for less mind-bending access to the functionality. They are directly
executable by just running them. Depending on the implementation and
the domain, they are used to build data structures, define dependencies,
run processes or tasks, communicate with other systems, or validate user
input. The syntax of an internal DSL is constrained by the host language.
There are many patterns—e.g., expression builder, method chaining, and
annotation—that can help you to bend the host language to your DSL. If
the host language doesn’t require recompilation, an internal DSL can be
developed quite quickly working side by side with a domain expert.

Free download pdf