Syntactical sugar

  • Posted on
  • by
  • in

Many people write code and specify all kinds of what I call "syntactic sugar". These come in the form of largely punctuation characters especially in Perl. Such things are usually included for the benefit of the compiler or more correctly the parser. They are there to avoid ambigutity but a coding style of specifing all of the defaults so that it's clear is IMHO ridiculous. Humans and human understanding of languages uses short cuts, context and implied meaning. Write your code for the next human - not the parser.

So, for example, I encountered the following line of Perl code the other day:

if (scalar(@ARGV != 1)) { die "\nUsage:\nAD_auth.pl \%username\%\n" }

Here are some of the unnecessary syntactic sugar:

  • scalar is unnessesary. An array evaluated in a scalar context, returns the number of entries in the area. Comparing an array to a number like 1 is evaluating an array in a scalar context.
  • The () around @ARGV != 1. Parantheses used to specify correct presidence in mathimatical expressions - sure, but only as many as you need. Here however the parantheses are unnessesary. Sure some say "it's a function call therefore its parms should be enclosed in ()" I ask "why?". Do you always likewise do print ("a string") or do you do print "a string"?
  • The () around the boolean expression for if. It's require, unless if appears at the end...
  • The {} around the then portion of the if statement. Technically not needed as without them the die statement would be the only statement in the then block. However in practice I pretty much always use {} even if only one statement. I find that way too often I need to stick more statements in there and if so then {} are already there.
  • Needless escape of %: There is no need to specify \%. Oh, and this is a bad, non-portable practice as if they meant %username% as in expand the environment variable username well that'd only work in Windows.

How do I think this would be better written:

die "Usage: $FindBin::Script <username>\n" unless @ARGV == 1;

I believe the advantages are:

  • Dynamically obtaining the script's name instead of hard coding it
  • Specifying <username> is a more standard way of indicating that the user should fill in this parameter
  • Positive logic, with the help of unless. Unless is like if not. But I find too many nots become confusing. It took a little bit of time for me to feel comfortable with unless, to trust it was the right thing. But it's pretty much English - unless the array ARGV has only 1 element. Unless also reads better at the end of a line.