How to handle squid:S1695 - do not throw NullPointerException

java

(Steven De Groote) #1

Must-share information:

  • SonarQube 6.7.3
  • Aiming to comply with S1695
  • Rewrite code, which does exactly the same thing, just to workaround the problem

First of all, I want to note there is an issue with the description of this rule, at https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/resources/org/sonar/l10n/java/rules/squid/S1695_java.html
It notes that throwing a NullPointer requires the caller to explicity catch it. This is obviously incorrect, as NullPointer extends RuntimeException, and therefore does not need to be caught. I consider this a bug.

Here’s a piece of code that’s problematic:

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value)       
    {
    if (uiComponent == null) throw new NullPointerException("uiComponent");

This is a method that complies with interface javax.faces.convert.Converter, whose documentation states a NullPointerException MUST be thrown in this case. However, the sonar rule says we shouldn’t do so…

Following the suggestion to annotate the function argument with @NotNull, it actually adds another rule violation, as uiComponent==null supposedly always evaluates to false. This is of course also not the case, as the @NotNull is a javax.validations annotation.

I could rewrite the nullcheck to use Objects.requireNonNull(), but that does exactly the same as what happens now, just avoiding any rule violations.

This brings me to questioning of what is the purpose of this rule? Why would it be considered useful? And how should one program to comply with it?