flash
flash

Reputation: 1519

NullPointerException might be thrown as 'value' is nullable here sonar warning

I have a code like this and when I am running it under sonar, it always complain on this line value.contains("true")

String value = getValue("/data/" + set, property);
if (!Strings.isNullOrEmpty(value)) {
  if (value.contains("true")) {
    return true;
  } else {
    return false;
  }
} else {
  return false;
}

Here is the message it is giving me: NullPointerException might be thrown as 'value' is nullable here

I am already checking value for null check just above then why it is complaining inside? Am I doing something wrong?

Update:

After Andy's suggestion. I rewrote something like this:

String value = getValue("/data/" + set, property);
if (value!=null) {
  return Boolean.parseBoolean(value);
}
return false;

Upvotes: 0

Views: 3230

Answers (1)

Andy Turner
Andy Turner

Reputation: 140544

It's likely that sonar doesn't understand the semantics of Strings.isNullOrEmpty.

You can make it less confusing all round if you were to write the condition as:

if (value != null) {

It doesn't really matter if you call contains on an empty string.

Also, this:

  if (value.contains("true")) {
    return true;
  } else {
    return false;
  }

is more easily written as

  return value.contains("true");

Overall, you can write this as:

return value != null && value.contains("true");

Edit for your update: if you're using Boolean.parseBoolean, you don't even need the null check. parseBoolean returns false for a null input.

String value = getValue("/data/" + set, property);
return Boolean.parseBoolean(value);

Upvotes: 5

Related Questions