if( $splort = 0 ) { print 'narf!'; }
What makes this bug so nefarious is that it's syntactically correct, and the similarity of the assignment operator to the numerical equivalence operator makes it difficult to spot visually. Our brains are very good at pattern recognition, and fluent, literate people read words as discrete entities rather than processing each letter.
For years I was plagued by tracking down these frustrating bugs. There's a certain pleasure in discovering the reason for a malfunction, but the == bug is just annoying. You can't blame a miscalculation or design flaw, it's just a typo. Worse, most typos are caught by invalid syntax or, in the case of bad variable names, by strict. But not this one. At one point, I had even considered writing source filter to look for assignments that had a high probability of actually being comparisons.
While I was lamenting about this topic to a former boss, he casually remarked, "Ah, yes, that's easy. Just put the constant on the left."
I blinked. "What?"
"Put the constant on the left," he repeated. "You can't assign to a constant, so it's a syntax error if you say = instead of ==."
The simplicity of this solution astounded me. All I had to do was get in the habit of writing:
if( 0 == $splort )
If I screwed it up, it simply wouldn't compile, instantly identifying the error. Best of all, it works the same for C, Java, PHP and other languages which I have used in the course of my career. Since then, I have made it my mission to point out this tip to fellow programmers, and I have been surprised that so few have ever considered it. Once they do, I am hailed as a genius. Which is why I like this trick even more.
In conclusion, one of life's most important lessons is that complex problems can often have ridiculously simply solutions, and often it takes the eyes or ears of another person to see them.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Avoiding the == blues
by BrowserUk (Patriarch) on Dec 29, 2004 at 19:41 UTC | |
by tye (Sage) on Dec 29, 2004 at 19:59 UTC | |
by friedo (Prior) on Dec 29, 2004 at 20:00 UTC | |
by gaal (Parson) on Dec 29, 2004 at 20:26 UTC | |
by Anonymous Monk on Dec 30, 2004 at 10:07 UTC | |
Re: Avoiding the == blues
by webfiend (Vicar) on Dec 29, 2004 at 23:02 UTC | |
Re: Avoiding the == blues
by Mutant (Priest) on Dec 30, 2004 at 10:27 UTC | |
by TimToady (Parson) on Dec 31, 2004 at 18:12 UTC | |
by Anonymous Monk on Jan 01, 2005 at 19:16 UTC | |
by Baz (Friar) on Jan 01, 2005 at 20:25 UTC | |
by aquarium (Curate) on Dec 31, 2004 at 14:27 UTC | |
Re: Avoiding the == blues
by SolidState (Scribe) on Dec 30, 2004 at 08:37 UTC |