Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Literals In If Condition

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?

like image 681
Walery Strauch Avatar asked Jan 10 '14 13:01

Walery Strauch


People also ask

What is literal in Java with example?

In simple words, Literals in Java is a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ''/count is assigned an integer value in the following statement. // Here 100 is a constant/literal.


1 Answers

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)

like image 187
lauksas Avatar answered Sep 27 '22 19:09

lauksas