Home > Back-end >  getTextContent() through "Null pointers should not be dereferenced"
getTextContent() through "Null pointers should not be dereferenced"

Time:10-05

I have a below method where we are using "getTextContent()" to get text content of the current node.

if (getElement(Details, null, "AMB") != null) {
            payload.put("<String>",
                    getElement(Details, null, "AMB").getTextContent().trim());
        }
        

I am always getting sonarqube error "Null pointers should not be dereferenced" Get emement method are below

private Element getElement(Node node, String errMessage, String... paths) {
        NodeList nodeList;
        Element element = (Element) node;
        for (String path : paths) {
            nodeList = element.getElementsByTagNameNS("*", path);
            if (checkList(nodeList)) {
                element = (Element) nodeList.item(0);
            } else {
                if (errMessage != null) {
                    log.error("Unable to read node element {}", errMessage);
                }
                return null;
            }
        }
        return element;
    }

I am not sure How I can handle this condition. I tried to put another "if" inside if condition. But again sonar qube through more error

Could you please help some one it is blocker to me.

CodePudding user response:

I suppose, the fact that you have a conditional like getElement(Details, null, "AMB") != null hints to the code audit tool that the method getElement may return null. In that case, the actual implementation code of the invoked method is not relevant.

Therefore, the tool produces a warning because the subsequent getElement(Details, null, "AMB").getTextContent().trim() dereferences the result of a call to getElement without a null check.

You seem to assume that two subsequent invocations of getElement(Details, null, "AMB") will return the same result, hence, the preceding test is sufficient, but code audit tools normally do not make such an assumption.

The simplest way to fix this, is to use a local variable to hold the result, which is generally to prefer over repeating expressions.

Element e = getElement(Details, null, "AMB");
if(e != null) {
    payload.put("<String>", e.getTextContent().trim());
}

This should be sufficient to convince any code checking tool that the condition and the subsequent use refer to the same value, hence, e can not be null at the e.getTextContent() invocation.

CodePudding user response:

You could try to use Optional . For example

  Optional<Element> ambElement = Optional.ofNullable(getElement(Details, null, "AMB"));
  if (ambElement.isPresent()) {
    payload.put("<String>", ambElement
      .map(e -> e.getTextContent())
      .map(s -> s.trim())
      .orElse(null)
    );
  }
  • Related