“Yoda Conditions” (from: stackoverflow – New programming jargon you coined?)
Posted by Jeroen Pluimers on 2010/05/25
Having done quite a bit of C and C++ work in the past, I often still use “Yoda Conditions”, especially in environments where you have both = and == as an operator.
So, in a boolean expression, I often put the constant to test in front of the test.
I recently learned at stackoverflow that quite a few people call these “Yoda Conditions”:
“Yoda Conditions”— the act of using if(constant == variable) instead of if(variable == constant), like if(4 == foo). Because it’s like saying “if blue is the sky” or “if tall is the man”.
Thanks to dreamlax for helping me find that.
For instance, in C#, consider this code:
bool a; if (a = true) // Warning: "Assignment in conditional expression is always constant; did you mean to use == instead of = ?" Console.WriteLine(a); bool b; if (a = b = true) // No Warning! Console.WriteLine(a);
Both if statements will happily hop into the “then”, and write true to the console.
The first statement will get you a compiler warning, but the second won’t!
Code inspection, pair programming, turning on warnings, etc will help you prevent these problems.
But using Yoda Conditions will generate a compiler error in stead of a warning.
Looking at the comments on stackoverflow, lots of people seem to object to Yoda Conditions.
But there are other situations where the order of things is ‘constant value, expression to test’ too.
- Unit testing: for instance JUnit, NUnit, DUnit and their father SUnit all have an Assert class that has assertEquals methods with parameters in the order “expected, actual”
- When testing reference.Equals(constant) and the reference can be null, it is wiser to turn it into constant.Equals(rerference)
So are Yoda Conditions really thad bad?
What’s your take on this?
PS: Since I use many languages and environments (always pick the best tool for a job!), I tend to:
- Use Yoda Conditions in other languages too
- Always have parentheses around boolean expressions
The reason is that languages do differ in what they allow and require. Finding a common denominator that works in most languages saves a lot of energy.