I just read this technique in a book, and I can't believe I never thought of it before (perhaps because I have not used many languages that require "$x == 5" for evaluation). Anyone who has used PHP or a similar language for really any length of time has made the mistake of writing code like this:
Code: Select all
if ($x = "value") {
//do something
}
It can be hard to spot the problem. The "Do something" part will always run. That is because I just assigned "value" to $x, instead of checking to see if $x was equal to "value"! Since an assignment always returns true, this IF statement will always run. These can be terrible bugs to track down, because your brain sees the = sign, and since you see so many single = signs, your brain accepts it as correct and moves on. I have sometimes debugged a script for hours trying to find what is wrong before noticing it.
So what can you do to make sure this won't happen? Change to a language that doesn't allow assignment in conditional expressions! Just kidding of course(although I do really wish they would make code like this illegal, like in Java and C# so that you could actually perform equality checks with only one =)!
Make a habit to always put your literals on the
left[/i] side when you are comparing values, like this:
Because if you only enter one = sign, you will have this:
Since you obviously cannot assign a variable to a literal, this causes a compiler/interpreter error! This is an extra level of error detection.
I am working on getting into the habit of this as we speak! It may take time to break, since I have been doing it the other way around for years
