API DSL – When is an API Considered an Embedded DSL?

apidsl

What is the difference between an API and an embedded Domain Specific Language (DSL)?

Is it just syntax?

Consider an API like OpenGL. How is that different from a graphics DSL?

In other words, if an API is sufficiently complex, can it be considered an embedded DSL?

Best Answer

The distinction is hard to make, and depend of the language used. It is also subjective.

In clojure, you can define APIs which look like a DSL. For exemple, hiccup allows you to generate html:

(html [:span {:class "foo"} "bar"])

This can be considered as a DSL with a lisp syntax. The fact that html could be a macro gives it the same amout of power as if you were writing a html templating lib with s-expressions (see sxml)

In python, the same API may look like:

html(["span", {"class" : "foo"}, "bar"])

html is a function. Its argument will be evaluated first, and then the function call will happen. The fact that the python syntax is more specific, and the python semantics are more strict means that this expression is harder to interpret as a DSL independent of the language.

A classic language representation is a tree like data structure and an eval function called recursively on its nodes. LISP languages makes this tree structure very apparent, so any nested function call is indistinguishable from a built-in language feature. That is why the LISP community speak about DSLs for almost everything.

I believe programming is about providing useful abstractions. I find that looking at everything you build (a lib or even the UI of your application) as language elements helping people to solve a complex problem is an effective way to design most things. With this perspective, I assert that every libraries are DSLs, but some of them are poorly designed :-)

Related Topic