MiniSnippet of the Day - equals NullPointerException

Posted by Mike Haller on Saturday, March 3. 2007 at 17:46
MiniSnippet of the Day - equals

Codesmell:
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.



Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
 
Submitted comments will be subject to moderation before being displayed.
 

About

My name is Mike Haller and I'm a software developer and architect at Bosch Software Innovations in Germany. I love programming, playing games and reading books. I like good food, making photos and learning and mentoring about the craftsmanship of commercial software development. Stack Overflow profile for mhaller

Quicksearch