Syntactic Saccharin

As I learn a language I’m always a bit leery of apparent syntactic sugar. Consider the following snippet of CoffeeScript:

if typeof num is not 'number'
  console.log 'not number'
if typeof num not 'number'
  console.log 'not number'
if typeof num != 'number'
  console.log 'not number'   
unless typeof num is 'number'
  console.log 'not number'

Reading them, they could, depending on the implementation, all be semantically the same: show the message if the variable isn’t a number. However if you’re familiar with CoffeeScript you’ll know that this isn’t the case at all. CoffeeScript generates JavaScript, so lets see what you get for JavaScript…

if (typeof num === !'number') {
  console.log('not number');
}
if (typeof num(!'number')) {
  console.log('not number');
}
if (typeof num !== 'number') {
  console.log('not number');
}
if (typeof num !== 'number') {
  console.log('not number');
}

Ok, so not is a unary operator, and the first two don’t work out at all. The last two, are equivalent, so unless is syntactic sugar.
Ruby offers, if ... else, if modifier, unless ... else , and unless modifier, so you end up with:

if x == 1 then
    puts 'hi'
end
puts 'hi' if x == 1
unless not x == 0 then
    puts 'hi'
end
puts 'hi' unless not x == 0

That just seems a bit nuts. Certainly some are more or less expressive in different circumstances but I feel it’s more minutia to keep in mind. You need clarity and correctness in your code and when I’m dancing across several peoples code styles in several languages, the slight expressiveness boost, at the cost of ambiguity, just doesn’t feel like a win.

Some of the issue is in the language cultures however. When is the last time you saw a do { ... } while condition in Java? It’s there but never used.

If I didn’t think I would annoy most everyone, I’d have static code analysis complain about the use of unless and the if/unless modifier syntax.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s