Why My One Line if Statements Are Unusual

My one line if statements have been described as “um… unique” and “making me cringe”, but trust me, there is method to this madness; mainly, it’s practical for debugging. The sample code is in ActionScript, but should be self-explanatory in any language with similar semantics:

if ((data.length > 0) && server.enabled)
  { server.send(data); }

The average developer doesn’t include those extra braces on the second line, and in fact, many will even keep everything on one single line. (You could also pull the braces down so the block of code occupies a full 4 lines of code, but that seems highly unnecessary.)

if ((data.length > 0) && server.enabled) server.send(data);

The reason I add these otherwise unnecessary braces is primarily for debugging. Say in our sample code, the data isn’t arriving at the server; a good developer goes back to make sure the data is being sent in the first place. The following function looks correct (and as a side note should work in a white-space oriented language such as Python), but does not function as expected:

if ((data.length > 0) && server.enabled)
  server.send(data); trace("Data sent");
// or even
if ((data.length > 0) && server.enabled)
  trace("Data sent");
// But my personal preference allows for the additional code:
if ((data.length > 0) && server.enabled)
  { server.send(data); trace("Data sent"); }

A good developer is smart enough to add the required brackets when adding the “debugging code”. I prefer adding the brackets preemptively; the extra time it takes to wrap the code in brackets isn’t that valuable to me.

(I also have a personal philosophy that if, for, do, and while should always be followed by an open bracket containing code rather than just code on its own, but that just has to do with the way I view the language as functioning behind the scenes. But it’s more difficult convincing other developers based on those grounds.)

1 Comment

From: Jimmy Breck-McKye
2014-03-15 11:28

Wait, putting your conditional procedures in a new block all the time is ‘unusual’? If anything, I’ve rarely seen the obverse. Putting everything on one line makes the code unnecessarily dense, and breaking it up means you can see the structure of the logic from the ‘texture’ of the source itself, as it were.

Post a comment

All comments are held for moderation; Markdown and basic HTML formatting accepted.

(required, not published)