What is syntax sugar and how does it work?

Asked

Viewed 2,787 times

14

I have seen in some blogs the use of that term and would like to know:

1) The real meaning of this expression and;

2) How a syntax sugar as the example below in the language ?

for (Foo foo : listFoo) {
    //CÓDIGO AQUI
}
  • 7

    Do you want to know what "syntax sugar" means or do you want to know how this example of sugar works? If it’s both, you’re asking two completely unrelated questions and they should be separated.

  • Both. I will list them to better demonstrate my need.

  • 7

    So separate into two different questions. Syntax sugar is one thing, as the for works has no relation and cannot be in the same question.

  • Sorry, @bigown, but I believe a definition associated with an example will facilitate my understanding of the term.

  • 5

    But still they’re separate things, I don’t know why having the two information on different pages can complicate understanding. The organization of the site is damaged by two unrelated questions in the same place.

2 answers

17


Literally, syntax sugar is a type of construction made to "sweeten" the code, ie do something in a simpler way.

Considering his example of for-each. Before Java 5, the new "sweetened" construction and the introduction of generics in the language, here is an equivalent code:

for (Iterator i = listFoo.iterator(); i.hasNext(); ) {
    Foo foo = (Foo) i.next();    
    // CÓDIGO AQUI
}

The version with the for-each is certainly simpler and less susceptible to failure.


Sources:

10

In computer science, syntactic sugar is the syntax within a programming language that is designed to make things easier to read or express. This makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

Translated from: http://en.wikipedia.org/wiki/Syntactic_sugar

This for iterates on all elements of listFoo, placing at each iteration the current element inside the variable foo.

  • 13

    But it’s like coffee: some people prefer sugar-free, and some people use more sugar than coffee.

  • 4

    There goes the philosophy of each. On the one hand, doing something in various ways can complicate. On the other, it improves the power of expression of language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.