This approach is also known as "Yoda conditions" ("if true the condition is"), and its purpose is to catch the common error in C-like languages, where you accidentally use a single
= when you mean
==, causing an assignment. Because the return value of such an assignment is the newly assigned value, such a bug can go unnoticed, and surface only much later in the code, at a seemingly unrelated location, and seemingly at-random. Such bugs are obviously the worst kind you can have, and so the "Yoda" convention reverses the operands - a constant is not an lvalue, and accidentally putting one on the left side of an assignment causes a compiler error, which is good because it means the error surfaces early on, in an easy-to-debug way.
However, the Yoda convention has some significant downsides:
- It comes at the cost of readability. "If the number of items is 4" is easier to read than "If 4 is the number of items", and this is also true for code.
- It relies solely on convention; there is nothing stopping a programmer from forgetting the convention, and you're back to square one. In other words, the convention cannot be enforced, and so you still don't have any guarantees.
- It only works for comparing against non-lvalues. If you compare two variables, both sides are lvalues, and you're not winning anything.
At the same time, compilers have advanced, in such a way that they are now able to detect what is probably an unintended assignment in a condition - quite simply, if you use
= inside an
if condition, the compiler will throw a warning. This check is easy to automate and enforce: just turn on the relevant compiler flags in your build script to treat this as a fatal error. This, of course, works for any kind of equals-comparison, regardless of lvalues, and it doesn't compromise readability in any way.
You are most likely to find Yoda conventions used in older projects, and when it is in place, it's probably better to stick with it, but I would not recommend using it in new projects - the benefit today is practically zero, and it's not worth the sacrifice in readability.