Chapter 2
Exploit Fluency

In natural languages, fluency refers to spoken or written words that effortlessly and smoothly flow to convey the essence of a thought, concept, or an idea. Like those “hums” in speech or noisy words like “basically” in writing, anything that disrupts the flow hinders fluency. Likewise, a syntax is fluent if it’s smooth, flows well, and has as little noise or extraneous details as possible.

Fluent code isn’t necessarily short or concise, but it doesn’t contain anything superfluous. For example, this syntax is filled with noise:

 fetch.balance(12345678);

Though we may be used to it, we should recognize that the dot, (), and ; are there because a language may insist on it and not because they are essential. In comparison to that noisy syntax, the following is more fluent:

 fetch balance 12345678

Where possible, we should design code to facilitate that style.

When designing DSLs, aim for fluency, as it makes communication pleasant. It reduces the drudgery and enhances the effectiveness of what’s being conveyed. Programmers used to C-like languages are sadly accustomed to the ceremonies and noisy syntax, whereas programmers used to languages like Ruby and Haskell often enjoy more fluency. Kotlin, being a multi-platform language, offers nice flexibilities, with as little ceremony and noise as possible. When designing our own DSLs, we can exploit that.

To design code with fluency, we have to aim for the fewest elements. The user of a DSL shouldn’t be forced to write (), ;, dot, {}, classes, function declarations, or variable definitions using val or var.

If host languages give us options to avoid syntax like new, ;, (), ->, and the like, the specification feels a lot closer to a natural language than code. When designing our own internal DSLs, we have to exploit the flexibilities of the host languages to the fullest extent to achieve fluency.

As you’ll see, DSLs can enjoy fluency when hosted on top of Kotlin. Kotlin is a language of low ceremony. For example, it doesn’t insist on having ; at the end of each line. Functions that are marked infix can be called without a dot and parentheses. By using overloaded operators, where it makes sense, we can make the syntax of a DSL obvious.

In this chapter we’ll use a hypothetical banking application to look at some ways to design syntax that are fluent, thanks to these capabilities of Kotlin.

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

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