Avoid Literals In If Condition

Walery Strauch picture Walery Strauch · Jan 10, 2014 · Viewed 7.4k times · Source

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?

Answer

lauksas picture lauksas · Jan 10, 2014

Why don't you use:

public String getFoo() {
    String foo = System.getProperty("foo", "defaultFoo");

    return foo;
}

It will return "defaultFoo" if no property is found.

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperty(java.lang.String, java.lang.String)