Search code examples
javasonarqubebooleanboolean-expressionboolean-operations

How to fix the major issue in SonarQube "needlessly boxes a boolean constant"


I have this method in my project:

private static boolean isNAND(boolean value1, boolean value2) {
        return value1 ? !value2 : Boolean.TRUE;
}

but I got this major issue in SonarQube that I don't know how to solve it:

Method io.clouding.bendiciones.buenas.noches.Operador.isNAND(boolean, boolean) needlessly boxes a boolean constant

Solution

  • This means you should either do the following:

    a. Either change the return type to Boolean object type. This would depend further on what you do with object of type Boolean.
    b. Change the return value from return value1 ? !value2 : Boolean.TRUE; to return value1 ? !value2 : true; or return value1 ? !value2 : !value1;

    This can be simplified further. If i look at the table of return values, then i see this:

    value1 value2 result
    T        F     T
    F        T     T
    T        T     F
    F        F     T
    

    Which means it's equivalent to return !(value1 & value2)

    This is because while returning value, you are going to convert object of type Boolean to primitive boolean.