Charles Stevens
Charles Stevens

Reputation: 1582

Avoid Literals In If Condition SonarQube error

I am getting error like Avoid Literals In If Condition in sonarqube , and unable to find the proper solution to it.

     SingleWrapper singleWrapper=null;
      :
      :
      singleWrapper=createWrapper();
      :
      private void wrap(){
           if(singleWrapper != null){  //Here i am getting error.
             //do Something
                             }
                         }

I know this question seems to be repeated one but its not,because previously asked for String . Thanks for any help.

Upvotes: 1

Views: 1867

Answers (2)

Mithfindel
Mithfindel

Reputation: 4716

The description for the PMD rule reads:

Avoid using hard coded literals in conditional statements, declare those as static variables or private members.

While in most cases it is relevant (you don't want to have arbitrary hard coded string or numerical literals), in this case it is (IMHO) a bit too zealous, for checking against null is so widely used that it should probably be ignored by this rule.

Since this rule comes from PMD (not SQ internal engine), you could ask for an upstream fix - or just remove it from your profile if it really bugs you.

Note that this rule is part of the Controversial Rules set.

Upvotes: 0

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

It is because your static code analysis tool detects null as a hardcoded literal, which, rigorously, is true.

The recommended behavior is to declare a constant object like

final static Object NULL = null;

and use it like

if(singleWrapper != NULL)

But I haven't still met a developer doing this. In this case, I think you're OK and you can ignore the code check warnings. That's my 2 cents.

Upvotes: 4

Related Questions