Yoda Conditions

Try, you will

Have you ever heard about Yoda conditions?

Yoda conditions or Yoda notation is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement.

Example:

Usually a conditional statement would be written as:

if ($value == 42) { /* ... */ }
// Reads like: "If the value equals 42..."

Yoda conditions describe the same expression, but reversed:

if (42 == $value) { /* ... */ }
// Reads like: "If 42 equals the value..."

Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.

if (42 = myNumber) { /* ... */ }
// A syntax error this is and compile it will not

Since 42 is a constant and can not be changed, this error will be caught by the compiler.

Yoda conditions are criticized for compromising readability by increasing the cognitive load of reading the code.

Some programming languages do not allow variable assignments within conditionals and many compilers produce a warning for code.

References

Did you find this article valuable?

Support Gonzalo Federico Fernández by becoming a sponsor. Any amount is appreciated!