Is syntactic sugar just tasty, or does it actually improve the language? Depends on your definition of "improve," I suppose. I just found a ruby idiom in Agile Web Development with Rails that can make a very common, wordy coding task short and clear. We often have to say "give me a thing, and if it doesn't exist yet, make one for me."
In Java:
public cart findCart() {In Ruby, this can be expressed as...
if (cart == null) cart = new Cart();
return cart;
}
def find_cart
session[:cart] ||= Cart.new
end
The or-equals operator belongs in a dynamic language, where expressions that evaluate to booleans can also be very nice rvalues. These three lines of code show off a few things about Ruby that might be mistaken for syntactic sugar, but actually make the language better:
- Avoid unnecessary punctuation.
- Clean syntax for hashes make them almost as readable as member data accessors
- Most statements are also expressions.
- Implicit returns.
It's delicious... and nutritious!