Yoda condition | if(null == x) or if(x == null)?

By | September 15, 2023

Yoda Condition: Good or Bad

The term Yoda condition refers to a standard programming practice that says we must reverse the typical order of a conditional statement in code. It is named after the Star Wars character Yoda, who speaks in a unique way, where he switches the order of subjects and verbs in his sentences, like saying “Much to learn, you still have” instead of more the typical “You still have much to learn“.

Yoda Condition in Java

In most of the programming languages a single equal sign (=) is used for assignment, while the double equal sign (==) is used for comparison. Yoda condition says, to flip the order of operands to avoid the accidental assignment.

Below, we can see that, if by mistake someone uses the single equal sign (=) in the conditional statement if(x == 5) then instead of comparison, the value “5” will be assigned to x.

Java
/**
 * Non-Yoda Condition
 * 
 * @author paulsofts
 */
int x = 5;
if (x == 5) {
    // Code to execute if x is equal to 5
}

In order to avoid the accidental assignment, we use Yoda condition, where we reverse the order in the conditional statement. In the following code, we can see, if by mistake someone uses the single equal (=) sign, then we will get a Compilation Error, as we can not assign any value to a constant.

Java
/**
 * Yoda Condition
 * 
 * @author paulsofts
 */
int x = 5;
if (5 == x) {
    // Code to execute if x is equal to 5
}

The Yoda condition is less common in modern programming because most of the programming languages and code editors have features or linting tools that helps the developer to catch accidental assignments in conditional statements. However, it can still be found in legacy code or in situations where developers prefer this style for readability and error prevention. For example, Most of the Banking and Financial Domain still uses the Codebase, which was developed 10–20 years ago, since then we are modifying and updating the Codebases to meet up the today’s customer requirements. There we can find, these Coding Practices are still followed.

Leave a Reply

Your email address will not be published. Required fields are marked *