http://qs1969.pair.com?node_id=418058

One of the most common and frustrating bugs that can occur in programs in any language with C-derived syntax is the accidental substitution of "=" for "==". For example,

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.

Looking at code is similar. I find, in the case of this error, that my mind expects to see == inside a conditional, and that's what I see. Until about the 20th time, when I force myself to read each individual letter, and notice the mistake.

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.