简体   繁体   中英

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;

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM