Thursday, March 10, 2005

Syntactic Sugar

"Syntactic sugar causes cancer of the semicolon."
Alan J. Perlis

Introduction

Syntactic sugar are constructs added to a language, to make it easier for programmers to read and write program code. Examples of syntactic sugar in Java is the syntax for Strings, Arrays, Enumerations, Varargs and Enhanced for Loops.

Concept: Syntactic sugar are constructs added to a language, to make it easier for programmers to read and write program code.

Program

class Sweetened {
    public static void main(String[] args) {
        System.out.println("I'll keep " + "the damn computer.");
    }
}

The use of the + operator could be viewed as syntactic sugar for the concat method.

class Unsweetened {
    public static void main(String[] args) {
        System.out.println("I'll keep ".concat("the damn computer."));
    }
}

Output

I'll keep the damn computer.

Discussion

Syntactic sugar hides away a lot of the details of a program. You can actually work with String and Array objects without realizing you are doing object-oriented programming at all.

5 Resources

No comments: