« get your backstreet boys off my network! | Main | Over-Preparedness Vindicated! »

nutritious syntactic sugar

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() {
if (cart == null) cart = new Cart();
return cart;
In Ruby, this can be expressed as...
def find_cart 
session[:cart] ||= Cart.new

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!

Reader Comments (1)

I dunno, this reminds me of Perl's syntactic sugar - a bit obscure. Like, you'd definitely have to explain it to the junior guys, you know?

python's got a couple ways to do that that I think are sort of neat:

found_cart = myhash.setdefault ("cart", cart())

if myhash["cart"] already exists, you get it. Otherwise you get the second value. They use this syntax all over the place - ask for something, and pass in a default value to return if it doesn't exist. Pretty handy. But this code does initialize a cart that may be thrown away if the key already exists.

So, there's also a wrapper for the built-in hash, called defaultdict, that is smarter - rather than pass in a default value, you pass in a function that generates the default value.

myhash = defaultdict (cart)

Whenever you access anything in myhash that doesn't already exist, it calls cart() to set its value, and returns that.

12.15.2007 at 06:27 PM | Unregistered CommenterJohn

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>