Value before variable coding
Posted on September 2, 2005
Filed Under /dev/null/ | 59 views |
Lately I’ve been consciously reworking how I write one small chunk of commonly-used code. When it comes to comparisons I’ve always written them (and always seen them written) as:
if ( $variable == 10 )
{ doSomething(); }
However lately I’ve taken to writing these statements as:
if ( 10 == $variable )
{ doSomething(); }
Admittedly I find this second style harder to read and comprehend; right now it takes more conscious effort to work out what’s actually happening, so why do it? Compile-time error trapping.
The most common mistake I make when writing statemens like these, especially since I move back and forth between PHP, ASP, and C# routinely in a day, is to write them as:
if ( $variable = 10 )
{ doSomething(); }
Note the single = sign. While this statement is perfectly valid code it’s actually wrong: instead of comparing $variable to 10 I’m now assigning 10 to $variable. Hunting that sort of bug can be a real pain in the ass since it’s subtle, can look right at first glance (esp. if part of my brain is still thinking in ASP) and doesn’t generate a compiler error.
However if I write the statement as:
if ( 10 = $variable )
{ doSomething(); }
the compiler coughs up a hairball immediately and tells me exactly what I’ve done wrong. 10 is immutable, I’m not allowed to assign the value of $variable to 10. No debug effort, no frustration, just right to the problem.
Comments
Leave a Reply