Suppose you want:
if (number == 42) { /* ... */ } // This checks if "number" is equal to 42 // The if-condition is true only if "number" is equal to 42
Now imagine that you forget that there should be a double = , and you just write only one = :
if (number = 42) { /* ... */ } // This assigns 42 to "number" // The if-condition is always true
Such errors are quite common and difficult to detect in programming languages โโthat allow you to assign variables in conditional expressions.
Now consider changing the order of your state:
if (42 == number) { /* ... */ } // This checks if "number" is equal to 42 // The if-condition is true only if "number" is equal to 42
The behavior of 42 == number exactly matches the behavior of number == 42 .
However, if you make the same mistake mentioned above (you forget that there should be a double = , and instead you just write one = ), the behavior will no longer be like this:
if (42 = number) { }
Therefore, some people prefer to change the order of their conditions, as this makes a common mistake much easier to detect. Such โreverseโ conditions are known as the Yoda Conditions .
In programming languages โโthat do not allow you to assign variables to conditional expressions (such as Python or Swift), there are no advantages to using Yoda conditions, and they are usually not recommended to use them. In other languages โโ(like JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it still depends heavily on your personal preferences or any coding standards that your project requires.
Wordpress and Symfony are two popular open source projects where Yoda terms are part of the coding standards.
John slegers
source share