Menu

Yoda notation

This is an old post from 2013. As such, it might not be relevant anymore.

Everyone’s done it, they’ve missed the second equals sign in an if-statement and created an assignment instead. Much tutting, shaking of the head, and a little chuckle ensues as you realise your error. There is a thought amongst some that Yoda notation is the way to go, so named because it switches the comparative’s to produce errors instead of unexpected behaviour. Consider the following:

if ($theSkyColour = 'blue') {
	// This will always be called, because the value will be "returned"
	// Equivalent of if ('blue') {
}

If you would switch the comparatives around you would end up with:

if ('blue' = $theSkyColour) {
	// I will produce an error
	// PHP Parse error:  syntax error, unexpected '=' in file.php
}

So you immediately know there is something wrong and you can correct it before it lands in production. But is this the best way to go about it? Possibly, it’s a matter of opinion; it’s been around for years and has made its way into some of the largest PHP projects such as WordPress, Symfony, etc.

Disadvantages

  1. It’s harder to read: “Is the sky blue?” is much easier for us to understand than “Blue is the sky colour?”.
  2. Is maintainability more important than a potential bug? I’m sure there will be people on both sides of the fence, and some in the middle collecting splinters.
  3. Nowadays IDE’s tend to prevent this kind of thing from happening, you can set them to give warnings on assignments in conditions.
  4. You can use a piece of software like PHP Code Sniffer in your build tool and reject anything that contains these potential nasties.
  5. And, most importantly, it isn’t a silver bullet; it will do nothing to prevent the code below from being incorrect or error’ing:
if ($foo = $bar) {
	// I am always run and no errors are ever thrown
}