Search code examples
javasemanticsjava-8

What are "sugar", "desugar" terms in context of Java 8?


I hear about 'sugaring' and 'desugaring' more often in Java 8, what do these terms mean? Are they conceptual or syntactical?

Some examples:

Default iterated loop resugaring to java

Observations about syntactic sugar in compilation.


Solution

  • sugar, in programming, usually refers to those sweet additions, mostly shortcuts, that make some constructs easier to type and to read (the latter being, in practice, the most important during the life cycle of your program).

    Wikipedia has a definition of syntactic sugar but you should note that not all sugar is, in essence, syntactical (not all recent sweet additions were just compiler changes).

    Here are a few examples :

    • the postfix and prefix increment operators (i++ and ++i). Their only purpose is to avoid writing an additional statement. They're pure sugar.
    • +=, |=, &=, etc. are made of the same kind of sugar.
    • Implicit conversion between primitive types and objects is sugar too.
    • type inference is sugar too.
    • Lambda expression, coming with Java 8, is some other kind of sugar (this one not just syntactical)

    Java is widely seen as not being concise enough, especially compared to modern languages. That's why those additions that help make the code faster to read are welcome.

    To finish, I'd just note that while a lack of sugar can make your program fat, an excess of sugar, leading to many different ways to write the same things, can make your language queasy and your program less coherent and harder to maintain. Another kind of sugar, API sugar, is most often a plague which makes the API harder to grasp, especially when it's made of additions (overloading for example).

    This being said, desugaring refers either to

    • the process by which you remove all that is redundant in a language
    • the process by which a code processor finds out what's behind a sugared statement (this may for example involves type inference)