52

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".

13
  • 1
    I never ever write code like that but to be fair "if chocolate is the flavor of the cake" does sound natural. Natural language is more flexible. May 5 '11 at 23:17
  • 4
    @Rick It might sound natural in language, but you can't deny that when you see code like that, you have to stop first (maybe only for a second) to think what is it that it's trying to do. May 6 '11 at 1:45
  • 4
    @Edgar Gonzalez: Agreed, I am firmly against it in code. May 6 '11 at 1:52
  • 5
    Chapter 19 of Code Complete 2nd Edition (under the section "Boolean Expressions: Common Problems With Boolean Expressions") actually recommends this practise for the exact reason stated in many of the answers here: to prevent assignment in C-derived languages when comparison was meant.
    – CraigTP
    May 6 '11 at 10:09
  • 6
    I've often seen these referred to as "Yoda Conditions"
    – Brian
    Sep 12 '12 at 20:58
91

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.

13
  • 4
    I remember when designing a language (long time ago) that we specifically made := be the assignment operator (with == for equality test) in order to avoid this sort of trouble. May 5 '11 at 23:37
  • 7
    I have written many, many, lines of code, and I have never accidentally typed = instead of ==. The difference is so accentuated everywhere that i've just never got them confused. On the other hand, I have read many pieces of code that are confusing or otherwise hard to understand. As such, I would put the priorities on the readability :). Regardless, good answer.
    – crazy2be
    May 6 '11 at 0:22
  • 7
    Yet another good reason to use -Wall -Werror or your compiler/interpreter's equivalent. There are very few situations where an assignment inside a condition is correct, let alone more readable. A lot of languages don't even allow it. May 6 '11 at 3:21
  • 8
    Pedantic: While if($foo = 1) evaluates to true in some languages, in PHP it evaluates to 1 instead; if($foo = 20) evaluates to 20; if($foo = 0) evaluates to 0, which unlike the others is false. This can add a whole 'nother layer of complexity to the bug.
    – Charles
    May 6 '11 at 5:00
  • 3
    Actually, the WordPress Coding Standards DOES call for Yoda Conditionals: codex.wordpress.org/WordPress_Coding_Standards#Yoda_Conditions
    – Tom Auger
    Sep 18 '12 at 14:46
14

It's a defensive coding mechanism meant to prevent an accidental use of the assignment operator.

Consider a misuse/error of the assignment operator in place of the equality operator

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

The above conditional would always return true, but that's probably not what the original programmer had in mind. Consider, in it's place, this

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

Here, PHP (and most other languages) would refuse to run, as it's impossible to assign anything to the fixed value of 1. By coding up all the conditional statements this way, you automatically ensure no accidental usage of an assignment operator in a conditional.

10

I like using that convention in java to remove the possibility of a null pointer exception. So something like this won't cause you any problems or need any extra code:

String foo = null;

if ("bar".equals(foo))
{
    //Do something
}
3
  • 3
    I like this, but I hate the general idiom. May 6 '11 at 3:35
  • 3
    If a null value is not valid by that point in code you should have already checked for it anyway or designed your code in such a way that a null value would be impossible.
    – Ed S.
    May 7 '11 at 20:03
  • 6
    this seems like an easy way to mask problems. Dusts aren't cleaned by shrugging them inside the carpet.
    – Lie Ryan
    Jul 13 '11 at 15:53
1

In practice, many compilers will give you a warning if you write "if (x = 1)" instead of "if (x == 1)" because it is most likely a mistake.

With Clang, you can avoid the warning by effectively telling the compiler "I mean it, and I know what I'm doing", and this is done by writing "if ((x = 1))". Note the extra parentheses. That works in other situations as well. if (false) statement; may give you a warning that the statement is never executed; if ((false)) statement; doesn't give that warning.

PS. Many languages nowadays require that the expression in an "if" statement is boolean, without any automatic conversion. In "if (x = 1)" the expression has type "int" so it won't be accepted, except for the rare case "if (bool1 = bool2)".

1
  • I like that a lot! I avoid the following, completely legit idiom in PHP because I always get warnings in my IDE: if ($array = getSomething()){ // ..so something with $array }
    – Tom Auger
    May 22 '19 at 13:57
-1

if ($variable == 'constant')

Because you spend more time reading code than writing it (see https://www.goodreads.com/quotes/835238-indeed-the-ratio-of-time-spent-reading-versus-writing-is), and this form is easier to read.

Although User8 has a valid argument to have the constant first; that's reasoning about what to do from the code writer's perspective. Normally, there are less experienced coders reading code, and they need all the help they can get in matching the natural order that would have the constant laste. (And of course, good language design and compiler checks overcome the stated problem).

4
  • good language design and compiler checks overcome the stated problem Except when they don't. The entire purpose of Yoda conditions is to act as just one tool to prevent the creation of bugs, not merely hope they are discovered by something before causing problems. Mar 17 at 10:30
  • @AndrewHenle That was in brackets, because that isn't my answer, but food for thought. Different people have different circumstances and are quite free to apply accordingly. Mar 18 at 0:04
  • -1 for: reviving a very old question, adding nothing new to the pool of knowledge, and generally coming across as arrogant and superior. That's not really the culture here. You can do better.
    – Tom Auger
    Mar 26 at 17:58
  • @TomAuger I'm a humble answerer, with no world-domination ambitions. Kindly point out which section of my answer is at fault and I will endeavor to improve it for the community. Apr 4 at 12:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.