Defensive coding: Null-safe string comparisons
One of the most valuable tips I received why having my Java code reviewed was to change this code:
if (merchant.getSalesChannel().equals("Mexico")) {
/* … */
}
to this:
if ("Mexico".equals(merchant.getSalesChannel()) {
/* … */
}
Everything in Java is an object. Thus, a simple string literal immediately creates a new object. We are sure that a literal is not null.
The other part of the equation might surprise us with a null. Who knows what that getter might return? Most likely it is some value from the database. Are we sure that the value was properly retrieved? Are we sure there’s a NOT NULL
constraint on the database column? We can never be sure.
So if we want to compare a variable to a string literal, let’s use the null-safe style proposed in the second listing above.
Further reading:
https://stackoverflow.com/questions/43409500/compare-strings-avoiding-nullpointerexception/43409501
https://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html