Created
September 2, 2010 14:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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! */ } |
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");
}
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
fixed :)
But mine was real code too :P
$DeathStar2 = new DeathStar(); //The Empire Strikes Back!
your code doesn't look like PHP - is it Ruby?
yes it is ruby... I likes me some ruby every once in a while
Uncle Bob doesn't like it when people code that way:
http://thecleancoder.blogspot.com/2010/09/john-macintyres-clean-code-experience-1.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But then you end up with inconsistant code :P