or what “syntactic sugar” is.
Java5 gave us syntactic sugar. Is it really sweet or just bad for your teeth?
What we got:
Varargs - I think I’ve said enough on this, so let’s advance to the for-loop
Instead of
Iterator iter = coll.iterator();
while( iter.hasNext() ){
Object obj = iter.next();
…
}
we could do
for (Object obj : coll) {
…
}
This is not only shorter, it is also clearer:
- We state that we assume Objects in coll (well not a big surprise with Object)
- We don’t plan to call remove() on the Iterator.
- There is no such thing as an index.
What “index” I am talking about, the for-loop works also with arrays or anything that implements Iterable
Double [] ds = getValues();
for (Number n: ds) …
The syntactic sugar here is hiding something from you, but it is handy in some situations.
On the plus side we have less clutter, and easier refactoring. Imaging you change from an array to a collection, must of the code can be refactored easily by your IDE, but it cannot refactor a for running over an index to an interator on the collection. The enhanced for-loop thus makes you code more reaable and mantainable. The downside: Another syntactical idiom to learn.
Generics are not templates. Generics are compile-time only. So having List just saves you some keystrokes because you don’t have to cast manually. In this sense there are just sugar, but important one. I see the main benefit in Generics that the forced covariancy and autoboxing (without these it would be very hard to define classes that implement a generic interface) - on the other hand covariancy with out generics is pretty useless.
So the sugar puts some restrictions and also opens (see my remarks on varargs) ways of improving the language or the performance of its implementations. Also the syntax gets richer and some idioms become part of the syntax (Iterator). This doesn’t make a language more complex. If the idiom is in the language it is implicitly clear. I gibe you ne example:
I heard of a style guide that defined the naming of index-variables. They had to be named ‘ii’,'jj’, etc. (This is really useful, because you can search it more easily, I adopted it years ago and I still use it). So you need code-inspection to enforce this and you have to make people learn this. In a differnt project (not speaking of a different organization) it will be different. A programmer will be much more productive and the code will equally standardized when an array-iteration is build into the language.
So when I write for(int a :values) it is clear that I only care about the values for ‘a’ and that their actual position does not matter. This gives simplicity by raising expressivity. In absence of this I have to learn how to do it anyway and the idiom of doing so is also specific to the language, but I still have a questionable freedom of implementing it. This is no simpler than some additional syntax while more difficult to manage in a project.