org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:5.1.0.4882
SonarCloud is flagging code with java:S2259, indicating that a NullPointerException could occur because map() can return null. However, this is a false positive in this instance. The rule incorrectly identifies the potential for a null return, despite Optional.ofNullable ensuring that the code will not produce a NullPointerException.
Code Sample:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.Optional;
public class ExampleClass {
public static void main(String[] args) throws IOException {
Document document = Jsoup.connect("https://www.sonarsource.com/").get();
Optional<String> value = new ExampleClass().parse(document);
System.out.println(value);
}
private Optional<String> parse(Document rootDocument) {
return Optional.ofNullable(rootDocument)
.map(document -> document.getElementsByClass("ety5px91 css-1xx1qgu e1gts9nz0"))
.filter(elements -> !elements.isEmpty())
.map(Elements::last)
.map(Element::text);
}
}
Explanation:
In this example:
- The method parse(Document rootDocument) uses Optional.ofNullable() to handle the case where rootDocument could be null.
- Each subsequent map() operation is safely chained, returning an empty Optional if any step results in null, rather than throwing a NullPointerException.
Expected Behavior:
SonarCloud should recognize that Optional.ofNullable and subsequent transformations do not produce a NullPointerException, making this rule’s flagging here inaccurate.
Impact:
This false positive may lead developers to refactor code unnecessarily, impacting productivity.
Could you please review this behavior and suggest a way to handle such cases without suppressing the rule for legitimate cases?
Thank you.