Search code examples
spring-mvcsonarqube

Sonarcube :Null pointers should not be dereferenced


lets say DefaultMessageSourceResolvable is spring framework class and the method getCode() may return null

@SuppressWarnings("serial")
public class DefaultMessageSourceResolvable implements MessageSourceResolvable, Serializable {

    @Nullable
    private final String[] codes;

    @Nullable
    public String getCode() {
        return (this.codes != null && this.codes.length > 0 ? this.codes[this.codes.length - 1] : null);
    }

}

Using the getCode() method in another class Sonar Lint gives error:

A "NullPointerException" could be thrown; "getCode()" can return null.

//inside this test class we are checking the condition what the getCode() method return 
//and then performing some task 
class Test {

    DefaultMessageSourceResolvable error = new DefaultMessageSourceResolvable();

    if (error.getCode().contains("something"))
    //error.getCode() this may return null so sonar gives 
    //major  issue
    {
        //do something 
    }

}

How to fix this?


Solution

  • You need to check for a null reference before you use the String#contains method.

    class Test {
    
        DefaultMessageSourceResolvable error = new DefaultMessageSourceResolvable();
    
        // Java with no third party libraries
        String errorCode = error.getCode();
        if (errorCode != null && errorCode.contains("something"))
        {
            //do something 
        }
    
        // Java using the very popular "org.apache.commons.lang3.StringUtils" library
        if (StringUtils.contains(error.getCode(), "something"))
        {
            //do something 
        }
    }