Skip to main content

Place Literals on the Left

When comparing literals in a statement, when possible always place the already defined variable on the left of the expression.

Firstly, this ensures that no NullPointerException's will be thrown by definition.

class ComparisonTest {

private static final String CODE = "123";

public void compareValues(String valueToCompare) {
// valueToCompare in this case could be undefined and throw a NullPointerException
if (valueToCompare.equals(CODE)) {
... do something
}

// No NullPointerException will be thrown in this case
if (CODE.equals(valueToCompare)) {
... do something
}
}
}

Secondly, this also aids in removing any potential mistaken assignments.

if (variable = 5) {...} // Compiles and will assign variable
if (5 = variable) {...} // Won't compile - potentially catching a mistake
if (5 == variable) {...} // Compiles