SonarLint : Change this condition so that it does not always evaluate to "true"

Sergiy Medvynskyy :

Here is my code

@Override
protected void setValue(Object value) {
    if (Boolean.TRUE.equals(value)) {
        // do something for true
    } else if (Boolean.FALSE.equals(value)) {
        // do something for false
    } else if (null == value) { // got SonarLint warning here
        // do something for null
    } else {
        // for any other non-null and not Boolean object call the super method
        super.setValue(value);
    }
}

At the line marked by "// got SonarLint warning here" I get the warning: Change this condition so that it does not always evaluate to "true. How should I change my method to avoid this warning?

Snagtz :

If value is a Boolean and it is not TRUE nor is it FALSE then it must be null since a Boolean object can only be TRUE or FALSE. So if it doesn't drop into the first two if statements then value is always null, thus the sonarlint warning. In your case I would do something like this:

   if (value instanceof Boolean) {
        if (Boolean.TRUE.equals(value)) {
            // do something for true
        }
        else {
            // do something for false
        }
    }
    else if (value != null) {
        // for any other non-null and not Boolean object call the super method
        super.setValue(value);
    }
    else {
           // do something for null
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146575&siteId=1