Diana Amza
Diana Amza

Reputation: 303

Smart way in Java to test for a method value in a null-proof way?

Does anybody know whether there is a way in Java to compare method values without the need for a separate call to check that the method doesn't return null? Eg, given a class like

public class Person{
  private String name;
  public String getName(){
     return name;
  }
  //...other stuff here
}

and then in another class we have a test like this:

if (person.getName() != null && person.getName().equals(otherPerson.getName()){
  //do something
}

what I'm wondering is what's the cleanest way to do this? In classes that have 10 or more members it gets messy to run so many null-checks and then value-comparison-checks.

Any hints or ideas are much appreciated!

Thanks!

Upvotes: 0

Views: 298

Answers (4)

mcv
mcv

Reputation: 4429

This extra boilerplate is one of the major downsides of Java. Groovy makes this easier with the ?. operator. There you can simply do:

if (person.getName()?.equals(otherPerson.getName()){
  //do something
}

If getName() returns null, the ?. operator returns null and the expression is evaluated as false.

In Java, the best solution is probably using StringUtils from Apache Commons:

StringUtils.equals(CharSequence, CharSequence)

That allows you to do stuff like:

StringUtils.equals(null, "abc");

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298908

Use JSR-305's @Nullable / @Nonnull annotations. Most modern IDEs can check whether they are used properly and warn you if not.

Upvotes: 1

thecoop
thecoop

Reputation: 46108

You can use Objects.equals to safely equate null values to each other in Java 7:

if (Objects.equals(person.getName(), otherPerson.getName()) { ... }

Of course, this doesn't stop exceptions if person or otherPerson is null, for which you'll need to do your own null check beforehand. If you're not using 7, you could easily write your own version of this method.

Upvotes: 5

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

org.apache.commons.lang3.StringUtils.equals

Upvotes: 1

Related Questions