Single-line ‘if’ statements

Single-line ‘if’ statements

How to avoid problems without totally avoiding them.

Apple?s recent TLS bug highlights once again the dangers of writing single-line if statements.

Apple?s bug was caused by a common feature of C and languages that inherited its syntax (e.g. C++, Java, and JavaScript); the option to not use curly braces when only one statement is guarded by the if statement.

Image for postThe above two ?if? statements behave the same in C-like languages.

It?s very tempting to make use of this feature since it saves at least two characters (the curly braces) and usually a newline or two. But as we see in the Apple bug, if one were to accidentally attempt to add a second statement to the if block, without adding the curly braces, the added statement will be run regardless of the if block?s condition. On top of that, if the newly added statement is indented like the existing statement, it may look like it?s including in the if block, when it actually isn?t, making the bug tough to catch.

Image for postTop: Oops. Bottom: OK!

Many coding styles recommend just using curly braces, even for one line if statements. Afterall, if there are curly braces with each if statement, then it?s clear where the guarded block begins and ends. While this is safer, it is disappointing that we?re throwing away a perfectly handy feature. I?m a big fan of reducing the size of code, a couple curly braces and newlines here and there add up. But I?m not a fan of horrible, yet easily avoided bugs. Is there a better way?

Only use single-line if statements on a single line

The problem occurs when a single-line if statement is broken up into two lines. While the compiler sees this as one statement guarded by a single condition, humans often accidentally read this is an if block, whether there are curly braces or not, thanks to the indentation. Humans notice the indentation, the compiler does not.

If the statement you?re guarding is small, and not worth the extra heft of curly braces, just put it on the same line.

Image for postIt?s pretty hard to mess up reading this since there?s no indentation.

Then if it comes time to add a statement to this if, it?s clear that curly braces need to be added, since you already need to put the existing statement on a new line.

Image for postNice!

As a bonus, this is how it?s done in Ruby, note how they came up with this idea first?

Image for post


No Responses

Write a response