Menu

Syntactic Sugar

In comparing programming languages I’ve found myself anchoring on what I’m comfortable with and seeing everything else as either “low level and verbose” or “full of syntactic sugar and magical”.

I’ve recently gone from using mostly Java to using mostly Kotlin and I’ve learned that syntactic sugar is fucking awesome and the term doesn’t do justice to the big positive impact it has on my programs.

I’d like to illustrate with an example. I’ve been visiting the library lots lately so I’ll write a program to track which books I’ve borrowed:

data class Book(val title: String, val author: String)  
interface LibraryBooksDb {  
  fun takeOut(book: Book, due: LocalDate)
  fun putBack(book: Book)
  fun dueSoon(duration: Duration = Duration.ofDays(4)): Set<Book>
}
@Test fun dueSoon() {
  val bookA = Book("Jurassic Park", "Michael Crichton")
  val bookB = Book("Skin in the Game", "Nicholas Taleb")

  clock.setNow(LocalDate.of(2018, 3, 2))
  db.takeOut(bookA, LocalDate.of(2018, 4, 2))
  db.takeOut(bookB, LocalDate.of(2018, 3, 16))

  // Initially nothing is due.
  assertThat(db.dueSoon()).isEmpty()

  // Extend what 'soon' means to include more books.
  assertThat(db.dueSoon(Duration.ofDays(14)))
      .containsExactly(bookB)
  assertThat(db.dueSoon(Duration.ofDays(31)))
      .containsExactly(bookA, bookB)

  // When we approach the due date, books become due.
  clock.setNow(LocalDate.of(2018, 3, 15))
  assertThat(db.dueSoon()).containsExactly(bookB)

  // Returning them clears them from the list.
  db.putBack(bookB)
  assertThat(db.dueSoon()).isEmpty()
}

Kotlin shines here because the code is mostly about the problem domain: books and dates! The javax.time API is also fantastic.

But Java programmers will need to write equals(), hashCode(), and toString() functions to avoid this nonsense:

java.lang.AssertionError:  
  expecting: <[Book@91161c7]> to contain: <[Book@4c70fda8]>

My book class also needs a constructor, several extra modifiers, and some accessors yielding dozens of lines of boilerplate. Should we enforce that the title is non-null? What about the author? This code isn’t merely tedious to write, it crowds out my attention. I’m thinking about hash codes instead of books!

But to C programmers the Java programmers have it easy. Lacking the syntactic sugar of automatic garbage collection, C programmers need to consider object ownership protocols. Are these functions pass-by-value or pass-by-reference? What’s the maximum length of a book title? C can’t separate interface from implementation because that requires the syntactic sugar of polymorphism! The language is great in many situations but to use it is to think about the machine and not the business problem.

I’ve stopped thinking of syntactic sugar as gratuitous. Instead it raises the layer of abstraction I work at. Not only can I work faster, but I can also solve bigger problems.