Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created September 2, 2010 14:13
Show Gist options
  • Save gavinblair/562335 to your computer and use it in GitHub Desktop.
Save gavinblair/562335 to your computer and use it in GitHub Desktop.
Reversing the order of a condition to avoid hard-to-find assignment problems
<?php
//This is what I normally do:
if($something == "string") { ... }
//The problem is, if I accidentally miss an = then it would be an assignment!
if($something = "string") { /* uh oh! */ }
//To prevent this, get in the habit of reversing the order:
if("string" == $something) { ... }
//That way, if you miss an = and it becomes an assignment, it will throw an error!
if ("string" = $something) { /* you can't assign a value to a constant! */ }
@SeanJA
Copy link

SeanJA commented Sep 2, 2010

Well... Netbeans warns me about that type of thing, you might also run into errors when you have == instead of ===

ie:

'something' == true but 'something' !== true

@gavinblair
Copy link
Author

LOL just learned that these are called "Yoda Conditions".

More info about Yoda Conditions: http://wiert.wordpress.com/2010/05/25/yoda-conditions-from-stackoverflow-new-programming-jargon-you-coined/ (via @mikealmond)

@SeanJA
Copy link

SeanJA commented Sep 2, 2010

Yes they are yoda conditions, they are also an archaism from the times of C.

A reason to avoid this archaism:

http://stackoverflow.com/questions/2955304/why-many-programmers-use-integer-literal-on-left-handside-of-equality-operator/2955522#2955522

@gavinblair
Copy link
Author

ok, if (18 <= age) return true; is a little crazy. Definitely wouldn't do that!

@SeanJA
Copy link

SeanJA commented Sep 3, 2010

But then you end up with inconsistant code :P

@gavinblair
Copy link
Author

I would probably only use the Yoda condition in scary situations, like sending an important email. Situations where not making a mistake is worth the inconsistent condition.
if ("fire" == $command) {
$DeathStar->lasers->fire("Alderaan");
}

@SeanJA
Copy link

SeanJA commented Sep 3, 2010

Clearly you mean:

if 'fire' == command then lasers.fire

or you can do it this way if you are really paranoid

if command.==('fire') then lasers.fire

@gavinblair
Copy link
Author

fixed :)

@SeanJA
Copy link

SeanJA commented Sep 3, 2010

But mine was real code too :P

@gavinblair
Copy link
Author

$DeathStar2 = new DeathStar(); //The Empire Strikes Back!

@gavinblair
Copy link
Author

your code doesn't look like PHP - is it Ruby?

@SeanJA
Copy link

SeanJA commented Sep 3, 2010

yes it is ruby... I likes me some ruby every once in a while

@SeanJA
Copy link

SeanJA commented Sep 10, 2010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment