Avoid Literals In If Condition

java, pmd, sonarqube

Solution

What does Sonar try to say is that you should avoid hardcoded literals (like `null`) in the `if` condition.

Suppose the following example:

Let's say we have this `if` statement, for which Sonar warns with Avoid Literals In If Condition:

if (i == 5) { 
    //do something
}

By declaring the hardcoded literal as (`final`) variable with descriptive names maintainability is enhanced:

final int FIVE = 5;
if (i == FIVE) {
    //do something
}

and Sonar doesn't warn anymore.

Problem

This part of code is rejected by pmd in sonar: ``` public String getFoo() { String foo = System.getProperty("foo"); if (foo == null) { foo = System.getenv("foo"); } else if (foo == null) { foo = "defaultFoo"; } return foo; } ``` It says "Avoid Literals In If Condition". Can someone tell me what's wrong with this or what this rule try to effect?

Original source