Coding Style – ‘constant’ == $variable vs $variable == ‘constant’

coding-standardscoding-styleconditionsdefensive-programming

Lately, I've been working a lot in PHP and specifically within the WordPress framework. I'm noticing a lot of code in the form of:

if ( 1 == $options['postlink'] )

Where I would have expected to see:

if ( $options['postlink'] == 1 )

Is this a convention found in certain languages / frameworks? Is there any reason the former approach is preferable to the latter (from a processing perspective, or a parsing perspective or even a human perspective?)

Or is it merely a matter of taste? I have always thought it better when performing a test, that the variable item being tested against some constant is on the left. It seems to map better to the way we would ask the question in natural language: "if the cake is chocolate" rather than "if chocolate is the cake".

Best Answer

The main reason to do this (so-called "Yoda conditional") is to prevent accidents whereby you accidentally use an assignment operator (=) instead of the equal comparison operator (==).

That is, if you made the mistake of doing:

$foo = 5;
if ($foo = 1) {
  // Stuff
}

The statement will evaluate to true (or, in the case of some languages—like PHP—a truthy value) and you'll have a hard-to-find bug.

But if you did:

$foo = 5;
if (1 = $foo) {
  // Stuff
}

You'll receive a fatal error because you can't assign $foo to an integer.

But as you pointed out, reversing the order generally makes things less readable. So, many coding standards (but not all, including WordPress) suggest or require $foo == 1 despite the bug hunting benefits of 1 == $foo.

Generally, my advice is to follow whatever established coding standard there is, if there is one: for WordPress, that means using Yoda conditionals.

When there isn't, and it's impossible to establish one through consensus with your peers, it's dealer's choice.

Related Topic