We've all done it: snagged a cookie when mom wasn't looking, gone around Deadman's Curve a bit too fast. We've even let the car sit in a parking spot after the meter expires. Yes, we've all violated any number of the cardinal rules of programming, the ones that everyone agrees are bad. And we secretly liked it.
We've thumbed our nose at the rules of good programming, typed out code that is totally bad -- and we've lived. There were no lightning bolts from the programming gods. Our desktops didn’t explode. In fact, our code compiled and shipped, and the customers seemed happy enough.
That’s because bad programming isn't in the same league as, say, licking an electric fence or pulling the tail of a tiger. Most of the time, it works out. The rules are more often guidelines or stylistic suggestions, not hard-and-fast rules that must be obeyed or code death will follow. Sure, your code might be ridiculed, possibly even publicly, but the fact that you’re bucking conventions adds a little bit of the thrill to subverting, even inadvertently, what amounts more often than not to the social mores of pleasant code.
To make matters more complex, sometimes it's better to break the rules. (Shhhh!) The code comes out cleaner. It may even be faster and simpler. The rules are usually a bit too broad, and an artful programmer can improve the code by breaking them. Don’t tell your boss, but sometimes it makes sense to code your own way.
What follows is a list of nine rules that some may consider unimpeachable, but many of us break often, with both success and pleasure.
Programming habit No. 1: Using
The prohibition on using
goto dates to the era before many of the tools of structured programming even existed. If programmers wanted to create a loop or jump to another routine, they would need to type
GOTO followed by a line number. After a few years, compiler teams let programmers use a string label instead of a line number. That was considered a hot new feature back then.
Some called the result “spaghetti code.” It was impossible for anyone to read your code later and follow the path of execution. It was a jumble of threads, forever tangled. Edsger Dijkstra banned the command with a manuscript drolly titled "Goto Statement Considered Harmful."
But absolute branching isn't the problem. It's the tangle that results. Often an artful
return will offer a very clean statement about what the code is doing at that spot. Sometimes adding
goto to a case statement will produce something that's simpler to understand than a more properly structured list of cascading if-then-else blocks.
Sign up for Computerworld eNewsletters.