Remove Noisy Syntax

Users don’t like ceremony. Noisy syntax makes for a very unpleasant experience. Furthermore, users may be technical—engineers, data scientists, people with advanced degrees—but unlike programmers, they’re mainly interested in using the application and don’t care where to place a ;, dot, or (). When designing a DSL, we should strive to remove as much noisy syntax as possible from the eyes and hands of the users.

Suppose we’re designing fluent syntax for a DSL to be used in a banking application by a domain expert. To query for the balance of an account, the user may be asked to write something like this:

 fetch.balance(12345678);

That may not bother a programmer who has endured the syntax of C-like languages. However, we’ll receive no affection from our users if they have to key in that syntax. At the very least, they may be tempted to spank us with their little pinky that’s forced to type that ending ;. As designers of DSLs we need to do better, to get rid of the ., (), and ;—all the noisy parts.

The DSL user should be able to type in just the essence, like so:

 fetch balance 12345678

Achieving this level of fluency is incredibly easy and almost effortless in Kotlin.

First, Kotlin doesn’t care for ;, so just don’t tell the users about ; and we’re good. Unless they are recovering programmers, users will never ask if they need to place a ;.

Syntax like a + b is called infix notation, as opposed to prefix notation (+ a b), which is the syntax of languages like Lisp and Clojure. Infix notation is intuitive and less noisy.

Dropping the . and () takes a little effort. Those two symbols can be dropped if a function is marked with the infix accessor. Kotlin permits infix only on functions that have a receiver (member functions or extension functions) and take a single argument.

We can easily support the fluent DSL snippet syntax fetch balance..., by writing a singleton fetch with a balance function marked with infix:

 object​ fetch {
 infix​ ​fun​ ​balance​(number: Int) = println(​"Fetch the balance for $number"​)
 }

We defined a singleton with a lowercase fetch instead of the conventional Pascal-case Fetch in order to support the expected syntax. Instead of breaking away from the convention, we may also use a type alias, as we’ll see later in this chapter.

When designing DSLs, make extensive use of infix functions. Pause when writing a function and ask if it should be marked with infix—in other words, do you want the user to express the call to this function with little noise? The answer is almost always yes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.228