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.
This is a problem in languages that have both the = and == operators, and the result of an assignment itself is also a value (i.e. allowing a = b = true).
In C# this still can go wrong with booleans.
Chuck Jazdzewski wrote a posting “zero the value is not” back in 2008, and Dan commented that C# still can fail with booleans.
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.
For instance:
- 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?
I don’t think so. And reading the Yoda Conditions post by Clark Grub, he doesn’t either. He even adds a few more languages in his list (like JavaScript and Ruby).
What’s your take on this?
–jeroen
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.
via New programming jargon you coined? – Stack Overflow.
Filed under: .NET, C#, Delphi, Development, Java, Ruby, Software Development, Web Development Image may be NSFW.
Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.
