Syntactic Sugar

Structure and Interpretation of Computer Programs

Certain constructs are referred to as syntactic sugars. What does this programming term mean, where did it originate, and where do we draw the line between more meaningful changes? Syntactic sugars are useful but not necessary to achieve a certain model.

This page describes syntactic sugar, which improves the appearance of computer programs.

Introduction

First, let's turn to the classic book Structure and Interpretation of Computer Programs to look up the term syntactic sugar. The term "syntactic sugar" refers to "special syntactic forms" that are convenient "alternative surface structures." (11) In simple terms, syntactic sugars are a feature in a programming language that lets you express an idea in a more convenient way.

Structure and Interpretation of Computer Programs

Peter Landin

The term syntactic sugar was coined by Peter Landin, who was a brilliant computer scientist in Britian. Dr. Landin pioneered the use of lambda calculus as it applies to computer languages. He was also a prominent bisexual activist for the Gay Liberation Front, for which he was once arrested.

Peter Landin

Cancer of the semicolon

One famous saying about syntactic sugar is: "Syntactic sugar causes cancer of the semicolon." Alan Perlis, another brilliant computer scientist, said this, and it alludes to how excessive "convenience" in a language can obscure some of its usage. For example, you could reach for a syntactic sugar approach rather than using a better, less obvious tactic.

Epigrams in Programming

Abstractions

Question and answer

How can you draw the line between meaningful abstractions in your logic and convenient syntactic sugars in the language? I think what you should aim for is a model that closely resembles your problem space: if a construct denotes part of your problem, then it is more meaningful than a syntactic sugar. Typically, syntactic sugars are more superficial.

The C# programming language

Examples of syntactic sugar. Where can we see syntactic sugar in popular programming languages such as the C# language? Two places in the C# language come to mind: the using statement, which is sugar for a try-finally construct; and the lock statement, which compiles to a try-finally statement with monitors.

Using Statement Calls Dispose Lock Statement Try Keyword Finally

Summary

Syntactic sugar in programming languages is useful in moderation, and likely harmful in excess. Most languages, including the C# language, have added syntactic sugar, and these features improve the language's readability for most programmers.

Literature
.NET