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.
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.
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.
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.
As a bonus, this is how it’s done in Ruby, note how they came up with this idea first☺