Wrath of comparison while coding in Java

I've encountered a lot of code where a variable is compared to a constant.

For example,  variable == "value".

This frequently results in issues when the variable is not of the correct type or is null. As a remedy, always compare a constant to a variable.

For instance,  "value" == variable, "value".equals(variable).

This way, even if the variable is unassigned or null, it will still return false by default because it is being compared to a constant and will most likely not change.


This appears to be a little and clear distinction, but I have encountered a lot of code where the former is more commonly used than the latter.

Subscribe to Bharath M Shetty

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe