AVOID NULL STRING COMPARISONS
What's wrong with this picture?
private final String aConstant = "testvalue";
boolean isEqualToConstant(String myParameter)
{
return myParameter.equals(aConstant);
}
Most Java programmers get caught in this construct at some point; the
problem is that if the myParameter variable is null, the comparison
will throw a NullPointerException. While we can always catch
exceptions, or test for null values before calling such functions,
there's a better way to improve our function:
return aConstant.equals(myParameter);
Simply by exchanging the two String objects in the comparison line, we
can guarantee that our method will never throw a NullPointerException
because the equals method will always be called on a non-null String.
The same rule applies for inline constants or other String comparison
methods:
return "testvalue".equalsIgnoreCase(myParameter);
If the myParameter String is null, the comparison will simply return
false.
So if you are ever comparing two Strings where you know one will be
non-null, always pass the unknown String as the method parameter, and
you'll never see those exceptions again.
------------------------------------------