Yoda Syntax – A Backwards Design Pattern for If Statements

Sometimes the penny drops and you realise there’s a childishly simple solution to a problem that’s been bugging you for years. And no, I’m not talking about my wife, I’m talking about Yoda Syntax.
Have you ever spent far too long hunting down an impossible bug in your PHP only to eventually track it down to a typo in an if statement. Chances are it was a misplaced ‘=’.
Named must your fail be before banish it you can
We all do it, and more often than we’d probably like to admit. Unless you don’t, in which case go pat yourself on the back, you’re a PHP rockstar. But as a simplified example say you wanted to write the following rather pointless function:
function is_it_red($colour) {
if ($colour == 'red') {
return true;
}
}
but what you ended up writing was
function is_it_red($colour) {
if ($colour = 'red') {
return true;
}
}
And as you know, whatever you pass into the second function (because you’re accidentally performing a variable assignment rather than testing for equality) it will return true.
Obviously this is an oversimplified example, but typos like this nestled inside large classes can prove hair-removingly difficult to track down.
Help you I can, yes
The solution to this is simply to alter the way you write if statements:
function is_it_red($colour) {
if ('red' == $colour) {
return true;
}
}
It looks odd, yeah, and you might have seen other people writing their if statements backwards in the past and wondered why. But the benefit of this is striking, and so simple that I’m left wondering why I never thought of it before.
Quite simply, if you make a typo and write the following:
function is_it_red($colour) {
if ('red' = $colour) {
return true;
}
}
You will cause a big nasty syntax error that you simply cannot fail to notice.
Parse error: syntax error, unexpected ‘=’ in /var/www/vhosts/example.com/httpdocs/what_colour_is_it.php


June 30th, 2010 at 2:11 pm
Nice tip – like you say, very simple!
Also nice to see ‘colour’ with a ‘u’