While perusing one of my oDesk contractor's Objective-C code tonight, I ran across a coding style issue that sent chills up my spine. We've all done it at some point in our careers, and why not? It's a pain to reach your right pinky finger over for those curly braces when you know you don't need them. Take it from me, though. If you're going to if, then brace, or else...
The 2nd and last time it happened to me was during the mid-1990's. The moment of realization of the idiotic oversight I had made remains etched in my memory not unlike that jump on the tennis court that left my foot turned backwards a few years ago. It was a simple helper method in an overgrown, tangled mess of a report object. It couldn't have been more than about 15 lines of code. Near the middle of the method, I had written something not unlike the following:
if( conditionA ) doConditionAThing(); if( conditionB ) doConditionBThing1(); doConditionBThing2(); if( conditionC ) doConditionCThing();
My mistake is obvious in this context, but imagine you're tracking your way through some 10-15 source files, many of which are over 1,000 lines long. Somewhere in that tangled, poorly-designed, mess of code is a bug, a nasty one that sometimes crashes the program. What's worse is the debuggers back then often had line number matching issues much more-so than they do today. As a result, the debugger never landed on doConditionBThing2(). It landed on the blank line after it.
After saying a lot of bad words and probably punching my monitor more than once, I finally threw out the debugger, stopped running tests, and started auditing my code. It took some time, but I finally noticed the missing braces for the if-statement causing the 2nd line of code after the conditionB if-statement to execute when it shouldn't.
It was a simple mistake that wasted countless hours. When you're under a deadline and sleep deprived, playing find the missing curly brace isn't as easy as it may look. It's a little lke rdng wrds wth vwls mssng. Your brain kicks in and fills in the blanks automatically.
Since that time, I've never written an if-statement without the requisite curly braces, and I warn any programmer working with me to do the same.