MiniSnippet of the Day - equals NullPointerException
Posted by Mike Haller
on Saturday, March 3. 2007
at 17:46
MiniSnippet of the Day - equalsCodesmell:
public boolean isFoo(String parameter) {
return parameter.equals("foo");
}
Problem: parameter can be null, thus throwing NullPointerException
Corrected:
public boolean isFoo(String parameter) {
return "foo".equals(parameter);
}
Solution: works also if parameter is null, no extra null-check is required (which could have been forgotten)
Always use a Constant as the object to call equals on, when the second object is variable.
There should be a Checkstyle or PMD rule for that.
