Satya's blog - Yoda conditions and spectacular failure

Aug 02 2012 22:58 Yoda conditions and spectacular failure

At http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html there is some talk of "Yoda Conditions". I sent an email to someone explaining what that is, as follows:

So, Yoda speaks "backwards", right? In many of the languages in common use, "=" is for assigning values to a variable and "==" is for comparison. A common bug used to be assignment instead of comparing. Usually assignment evaluates as "true" in the comparison context.

Suppose some variable 'i' is 3. "if i=5" will set i to 5 *and* cause the program to think that the condition has come about. But i was actually 3 and would have failed comparison when correctly written as "if i==5".

The code will execute fine, but not produce correct results. So some IDEs (code editors) warn you that you're assigning when you should be comparing. To help you when not using those IDEs (which is often), some programmers write "if 5==i" which is a perfectly valid comparison. If typed as "if 5=i" it will NOT COMPILE and thus will never execute and will never be subtly wrong.

Spectacular failure (crash, or 500 internal server error) is better than subtle failure (grade is B- where it should be B, or vice versa) because spectacular failure is immediately noticeable and doesn't lead you to think you have the right results when you don't.

Tag: geeky