What’s a Yoda Condition?
Let’s start this off by explaining what a yoda condition (or notation) is. Yoda conditions are when you do a conditional check (such as an if check) and you swap the constant and the variable around. For example, normally, you would do
length == 5 but a yoda condition would use
5 == length.
Why would anybody want to do that? To avoid human error. You see, in many C-based languages (especially older ones, plus several other languages), places that used conditional expressions (if, while, etc) would allow values that weren’t booleans to be used. Anything that evaluated as 0 was false, and everything else was true (assignments in most languages are expressions that evaluate to the value assigned, rather than expressions).
This could lead to accidentally typing
length = 5, which would always evaluate to true because it would set length equal to 5, which is a truth value. So, in order to avoid such silly mistakes, they would reverse it so the compiler would catch it. Compilers don’t like
5 = length. Continue Reading