Skip to content

Domain Specific Language(DSL)

Rajesh Khadka edited this page Dec 7, 2018 · 5 revisions

DSLs are small languages, focused on a particular aspect of a software system. You can't build a whole program with a DSL, but you often use multiple DSLs in a system mainly written in a general purpose language.

DSLs come in two main forms: external and internal. An external DSL is a language that's parsed independently of the host general purpose language: good examples include regular expressions and CSS. External DSLs have a strong tradition in the Unix community.

Internal DSLs are a particular form of API in a host general purpose language, often referred to as a fluent interface. The way mocking libraries, such as JMock, define expectations for tests are good examples of this, as are many of the mechanisms used by Ruby on Rails. Internal DSLs also have a long tradition of usage, particularly in the Lisp community.

People find DSLs valuable because a well-designed DSL can be much easier to program with than a traditional library. This improves programmer productivity, which is always valuable. In particular, it may also improve communication with domain experts, which is an important tool for tackling one of the hardest problems in software development. CSS is an excellent example of this, most people who program CSS don't consider themselves to be programming.

Anko is one of the implementations of DSL.

Let's create a DSL to release an application to the playstore.

class ReleaseHandler {
    var versionCode = 1
    fun incrementBuildNumber() {
        versionCode++
    }

    fun uploadApkToPlayStore() {
        print("uploading apk to playstore")
    }

    operator fun invoke(handler: ReleaseHandler.() -> Unit): ReleaseHandler {
        handler()
        return this
    }
}

var release = ReleaseHandler()
release {
    incrementBuildNumber()
    uploadApkToPlayStore()
}

If you look into the function kotlin fun release(handler: ReleaseHandler.() -> Unit) we have lamda expression as input parameter which is extension function of the ReleaseHandler. If you define function as extension function we can add manupulation over member variable and function. You can read more about the extension function.

we have directly called the kotlin release function because of operator function function

References:

  1. https://martinfowler.com/books/dsl.html
  2. https://javieracero.com/blog/internal-vs-external-dsl/
Clone this wiki locally