There are counterexamples. The "goto fail" security hole in Apple's SSL stack is one of the best instances. But if we're careful to avoid some of the gnarly issues of case statements and loops, we can insert good, absolute jumps that make it easier for the reader to understand what's going on. We can put in a
break or a
return that is cleaner and more pleasing for everyone -- except perhaps the
Programming habit No. 2: Eschewing documentation
One friend of mine worked for a hard-nosed boss who never wrote any code but understood just enough to know that every function must include documentation. If the programmers didn’t include a comment, they must be punished. So my friend wired together an Eliza-like AI to his editor, and voilà, every function had a few lines of "documentation." The boss wasn't smart enough to understand that the lines meant nothing, so my friend was off the hook. His code was officially documented. I think he even got a promotion!
Many functions and even some classes are more or less self-documenting. Functions with names like
deleteAll don't need another line or three to explain what's going on. Choosing the right names for the function is often good enough. In fact it’s better than writing long documentation because the function names appear in other places in the code. The documentation is in only one place. Self-documenting function names improve every file where they appear.
There are cases when it's worse to have documentation. When the code is rapidly changing and the team is refactoring like crazy, documentation can diverge. The code says one thing, but the documentation is explaining what happened four or five revisions ago. This often happens at the top of the code where someone wrote a nice summary of what's supposed to happen. The refactoring team may be careful enough to fix the comments on the functions they change, but they may not even see the comments at the top of the file.
When the code and the text diverge, the comments become worthless and sometimes even dangerous. In cases like these, good, self-documenting code is better without comments.
Programming habit No. 3: Jamming too much code on one line
One boss along my path to nirvana sent out a nasty email to the team. Suddenly, all of us must rewrite our code to follow very strict rules of style. The most dramatic requirement: Each action or step or clause must be on its own line. You couldn’t chain function calls together with dot syntax. You couldn’t have two or more clauses to the boolean in a branch statement. If you define a variable, put it on its own line. If you're doing a complex calculation, don't use parentheses. Put each fragment on its own line.
Sign up for CIO Asia eNewsletters.