top | item 13668792

Yoda Conditions

76 points| sloankev | 9 years ago |en.wikipedia.org | reply

79 comments

order
[+] kibwen|9 years ago|reply
One of the best bugs I've ever seen was in the game Dungeon Crawl Stone Soup. It's a roguelike, and a venerable old one at that, so the codebase is quite tangled and convoluted, with logic for everything in every corner. One of the worshippable gods in the game is Xom, god of chaos, whose effects are just as likely to kill their worshipers as to help them (frustrating for those who might actually want to win, but always good for a laugh). And somewhere in the main game loop was some bit of logic that was only ever supposed to activate while the player was actively worshiping Xom. Guess how this was accidentally implemented:

  if (you.religion = GOD_XOM) {
This actually made it to the live test server, where player save files are automatically upgraded to the most recent build, so anyone logging in immediately found themselves infallibly worshiping the god of chaos, every single tick of in-game time (renouncement is futile). Chaos indeed!
[+] paol|9 years ago|reply
Don't do this.

In languages where accidental assignment is possible (i.e. writing if(a=b) when you meant if(a==b) ), configure the compiler or linter to emit a warning in this situation.

For example in C, GCC will complain about this when compiling with -Wall, which you should be using anyway.

[+] hashkb|9 years ago|reply
The real lesson is for language designers, who for some reason love using equals for assignment. Lisp got it right a hundred years ago and nobody learned.
[+] kbenson|9 years ago|reply
There are useful cases for this. It's much less ambiguous in those cases if your language allows the definition of the variable in the same location, and scopes it. For example, Perl:

    use strict;
    use warnings;
    
    sub one { 1 }
    
    if ( my $one = one() ) {
        say $one; # prints 1
    }
    
    say $one; # compilation error, "Global symbol "$one" requires explicit package name"
This case is trivial, but when you want a temporary variable and don't want to clutter your scope, it can be useful.

That's not to say assignment and equivalence might not be better off with different operators, as noted by others here.

[+] brianwawok|9 years ago|reply
Eh, I think it is good in Java in cases where Null input is possible.
[+] busterarm|9 years ago|reply
Counterargument:

Do do this if the coding standards for the language/framework you're working in require it. Like WordPress.

[+] michaelmior|9 years ago|reply
While I don't disagree, curious to hear your reasoning for not doing this.
[+] MikkoFinell|9 years ago|reply
Also clang warns "using the result of an assignment as a condition without parentheses".
[+] mirekrusin|9 years ago|reply
Exactly, and use 'if ((a = b)) ...' in those rare cases when it's appropriate.
[+] devy|9 years ago|reply
What about PHP? It's in the coding standard in WordPress and Symfony... :(
[+] thefifthsetpin|9 years ago|reply
I'm fond of Yoda conditionals, but not for the commonly cited reasons. Mostly I just like that they promote the interesting/unpredictable part of the comparison to the front. I consider the safety from unexpected assignment, from null pointer exceptions, and the Star Wars reference all to be minor perks.

Take this example:

  function handle_request($http){
    if("OPTIONS" === $http.request.method){
      ...
    }else if("GET" === $http.request.method){
       ...
    }else if("PUT" === $http.request.method){
      ...
    }else if($http.request.method === "POST"){
      ...
    }
    ...
  }
Did you read $http.request.method four times? I bet not. Some of you may have read it the first time; I wouldn't have. But to know that the fourth block handled POST requests I made you read to the end of the line. That makes it harder to scan the code looking for the section that you want to change. In production code that I've seen, the predictable side of a comparison is often quite long.

What's especially bizarre to me is the reason people give when advocating writing in the last style. Yes, it verbalizes nicely as "Otherwise, if the http request method post, then..." But who internally translates their code to English to understand it? COBOL was designed to read like natural language. Do you enjoy programming in COBOL? If English-like syntax is desirable for code readability, why don't modern programming languages prioritize English-like syntax, too?

Greek mathematics got stuck because it remained a verbal, pictorial activity, Moslem "algebra", after a timid attempt at symbolism, died when it returned to the rhetoric style, and the modern civilized world could only emerge —for better or for worse— ... thanks to the carefully, or at least consciously designed formal symbolisms that we owe to people like Vieta, Descartes, Leibniz, and (later) Boole.

-- Dijkstra,

[+] selfsimilar|9 years ago|reply
In PHP I like using Yoda Conditions because there's a common idiom of testing assignment in the conditional:

    if ($value = getSomeValue()) {
      // Safely use value
    }
Yoda Conditions defend nicely against accidents when '=' and '==' can be used legally this way and honestly you get used to reading them pretty quick.
[+] YSFEJ4SWJUVU6|9 years ago|reply
Just wrap the condition inside another pair of parentheses; that should get any linter off your back without needing to deal with the annoying flipped conditions – and if someone doesn't know the code base has a 100% coverage of Yoda conditions, they might just think there's a bug on the line when seeing it for the first time (unless you add an explanatory comment each time, at which point the assignment inside the condition has bought you nothing, as you might just lift it on a row of its own before the if statement).

C++, for instance however has language syntax to prevent confusion when using this idiom – declarations inside conditionals:

  if (auto val = getval())
    foo(val); // executed only if getval() returned something that evaluates to true
              // in a boolean context
Considering that PHP already has the useless var keyword, they might just adopt something similar in the future

  if (var $val = getval()) {}
[+] efaref|9 years ago|reply
I've been coding for decades and I still find them jarring.

They're also a false sense of security as they won't catch:

    if $(value = $someOthervalue) ...
[+] ghurtado|9 years ago|reply
I don't see at all how you could call this a Yoda Condition: it couldn't be written any other way, as it would cause a syntax error.
[+] logfromblammo|9 years ago|reply
I was once officially reprimanded for using Yoda conditionals. That was at the same place that required this:

  if( booleanVariable == true )
  {
      ...
  }
  else if( booleanVariable == false )
  {
      ...
  }
  else
  {
      // Typically, this section would include an exact copy
      // of one of the above sections, as it was 3 years ago,
      // presumably to pad out the SLoC metrics.
  }
That place had its head so far up its own ass....

Equivalence is commutative. Please never complain about the order of its operands as "confusing" or "less readable". It just tells me that you're an ass, trying to enforce a coding convention that has no objective reason to exist.

[+] geofft|9 years ago|reply
I ran across a bug at $dayjob where someone was clearly trying to use Yoda conditions, but messed up differently:

    if "start" == argv[1]:
        ....
    else if "stop" == argv[1]:
        ....
    else if "reload":
        ....
    else if "status" == argv[1]:
        ....
I think it'd be harder to make this mistake with the conditions the right way around. (Also, never mind that the equality bug isn't even possible in Python.)
[+] jquast|9 years ago|reply
I wish python had case statements for this very problem. If the statement blocks can be defined by a common function signature, your example could use

  {'start':  fn_start,
   'stop': fn_stop,
  }.get(
    argv[1] if len(argv) > 1 else None,
    fn_undefined
  )(*args, **kwargs)
I used this in a demonstration terminal nibbles/worms video game clone, https://github.com/jquast/blessed/blob/master/bin/worms.py#L...
[+] koolba|9 years ago|reply
A similar but arguably more useful version of this is when you have two variables, one of which may be null. Traditionally you issue an if-condition test using the variable user input as the left operand but switching it handles the null case automatically.

Ex:

    Foo SOME_CONSTANT = <something-not-null>;

    Foo userSuppliedInput = <some-user-input-possibly-null>;

    // This can raise an null pointer exception
    if (userSuppliedInput.isEquals(SOME_CONSTANT) {
        // ...
    }

    // This can't raise a null pointer exception (assuming isEquals handles nulls properly):
    if (SOME_CONSTANT.isEquals(userSuppliedInput) {
        // ...
    }
[+] mikeash|9 years ago|reply
Objective-C is really fun here. Messages to nil are no-ops which return zero, which for booleans results in false. Thus, the conditional works just fine either way:

  if([userSuppliedInput isEqual: SOME_CONSTANT]) { ...
If userSuppliedInput is nil, the isEqual: returns false, and it works.

It gets really fun when both might be nil:

  if([a isEqual: b]) { ...
If a and b are both nil, then they're conceptually equal, but isEqual: still returns false because it's a mindless "always return 0 for messages to nil" thing that doesn't even look at any parameters passed in.
[+] nayuki|9 years ago|reply
I would say that the phrase "Yoda conditions" more appropriately describes Ruby's alternative form of if-statements:

    if x > 0:
        y += x
versus

    y += x if x > 0
[+] kentt|9 years ago|reply
One of the worst parts of Ruby. I can see the argument that it could be better to have

  save if valid
rather than

  if valid
    save
  end
but what I see 9 times out of 10 is

  things.do each |thing|
    foo
    bar
    baz
  end if valid
or

really.long.thing.that.i.try.to.parse.in.my.head if acutally_almost_never_happens

which is harder to read since I read top to bottom / left to right, but the flow is bottom to top and right to left

[+] yellowapple|9 years ago|reply
To clarify a bit: postfix conditionals actually originate from Perl, and are one of several things that Ruby inherited as a Perl descendant.

In Perl:

    if ($x > 0) { $y += $x }
versus:

    $y += $x if $x > 0;
[+] codr4life|9 years ago|reply
Not worth the effort; modern compilers are very helpful with identifying these kinds of slip ups; and they weren't really that common to begin with, not common enough to warrant the attention and energy sucked into this never ending argument. It's a rule for the sake of having rules, like so many others.
[+] MilnerRoute|9 years ago|reply
I didn't know abut "Yoda conditions," and thought it was going to be those "reversed" if statements that were so startling when I'd started coding in Perl.

      $days = 28  if $month eq "February";
[+] rocky1138|9 years ago|reply
I don't follow this convention, but something I do follow is naming things by type first. This makes it really easy to find in a long list of files in a folder.

Example: plantArrowhead, plantGuzmania, plantMarmo vs. arrowheadPlant, guzmaniaPlant, marmoPlant.

[+] alexeiz|9 years ago|reply
Yoda conditions suck. You don't compare a constant to a value of a variable to make sure that the constant has a certain value. Such comparison is backwards. Unfortunately it is extremely popular at Microsoft among C++ programmers. They seem to totally lack any sense of style. Sometime in the nineties the enforcement of Hungarian notation throughout the company had a long lasting damaging effect on their psyche they still can't recover from after all these years.
[+] oli5679|9 years ago|reply
Interesting idea this is.