-1

I have a simple method:

public String getValue(String tag)    {
    if (StringUtils.isBlank(tag))    {
        return null;
    }

    return tag.substring(tag.lastIndexOf('/') + 1).trim();
}

Which is then called later on like this:

String tag = node.getNodeValue(); <-- from org.w3c.dom.Node
String value = getValue(tag);

String price = getAttribute(param1, param2, getValue(value));

SonarQube is warning me about a NullPointerException:

"NullPointerException" will be thrown when invoking method "getValue()" <-- the second call

However, I fail to see how. The method by itself is null-proof. What is happening ? Is SonarQube unable to go down the StringUtils.isBlank method ? Or is it the getAttribute() method that will give me the NullPointerException, and the error message can seem misleading ?

Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
  • are you sure is not getAttribute that will generate the NPE? probably is warning you that the call to getValue can return null, and getAttribute will throw with that null value returned by getValue – Alberto Sinigaglia Jun 03 '20 at 15:02
  • Well, that is one of my questions: I quite don't know :( – Yassine Badache Jun 03 '20 at 15:06
  • Well, check the getAttribute function, or post it here – Alberto Sinigaglia Jun 03 '20 at 15:09
  • I know this isn't part of the question, but you have a logical error in your code. The line `String price = getAttribute(param1, param2, getValue(value));` should be `String price = getAttribute(param1, param2, value);`. While your code will work, it is doing more than it needs to. Lets say tag="foo/bar" then value will be "bar" after the call to get value in the second line. Then when you are getting price you are calling getValue("bar"), which will return "bar", but why waste the computer's time? – bcr666 Jun 03 '20 at 15:20
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zoe Apr 04 '21 at 11:43

2 Answers2

0

You are getting this warning because of the following line:

return null;

Why would you return null when tag is blank? I suggest you do it as:

return tag;

or maybe

return "";

However, your function will still remain prone to NullPointerException because tag may be null. To avoid the possibility of NullPointerException, I suggest the following implementation for your function:

public String getValue(String tag) {
    if (tag != null) {
        tag = tag.substring(tag.lastIndexOf('/') + 1).trim();
    }

    return tag;
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

If the string is null, you can´t invoke any method on it.

The trim method will trigger the null pointer exception:

 return tag.substring(tag.lastIndexOf('/') + 1).trim();

Consider using an Optional for the string: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Laura Liparulo
  • 2,849
  • 26
  • 27