Search code examples
javasonarqubesonarlint

Sonarqube : Boolean literals should not be redundant


I have the following nice one liner :

boolean outcome = count > 0 ? false : true;

But from sonaqube I get 'Remove the literal "false" boolean value'

The solution seems to assume you can re-write as a function

But even that function will have that simple one liner and put me in the same position, I don't quite understand how to fix ? Ideas ?


Solution

  • The issue is that you are doing extra gymnastics on an operation that already produces a boolean.

    If I write out what you have coded in full syntax:

    boolean outcome;
    
    if(count > 0){
      outcome = false;
    } else {
     outcome = true;
    }
    

    essentially, you are reversing the count > 0

    So try

    boolean outcome = !(count > 0)
    

    or even better

    boolean outcome = count <= 0