Curse of the Double Equals

stu42j on 2008-05-14T02:07:41

Every beginner programmer (of C-style languages) has to learn to deal with '=' (assignment) vs. '==' (comparison). Using = in an if clause is probably one of the most common early mistakes.

I'd like to think that I'm past that stage of my programming experience. However, about once a year I'll waste a couple of hours debugging to eventually notice the missing =.

I was working on some Javascript today and I had the feeling something was wrong with that if but my brain kept telling me to change the = to eq. Must be the jet lag from Ireland. Yeah, the jet lag. That's it, that's the ticket.


Perl::Critic?

Alias on 2008-05-14T03:40:49

Is there a critic policy for that yet?

Re:Perl::Critic?

ChrisDolan on 2008-05-14T06:45:51

I was about to say yes, but then I checked and, no, we don't have a policy for that. CodePro has one for Java and that's what I was thinking of. :-)

As someone else said, I always write "10 == $x" instead of "$x == 10". It takes just a little getting used to, but it's a MUCH safer style. In autoboxed scalars, it works well too: in Java, "10".equals(str) is better than str.equals("10") because the former handles null gracefully and the latter does not.

For consistency, I try to put the constant first for every infix comparison operator.

I'll add a P::C todo entry right now.

A Tip

davorg on 2008-05-14T05:09:39

If you're comparing a constant to a variable, then put the constant first in the expression.

if (10 == $x)

If you forget the extra '=' then most C-style languages will throw a compile-time error.

Can't count the amount of time that's saved me over the last twenty years.