All Downloads are FREE. Search and download functionalities are using the official Maven repository.

resources.report.rules.pmd.AvoidLiteralsInIfCondition.html Maven / Gradle / Ivy



AvoidLiteralsInIfCondition

AvoidLiteralsInIfCondition

Avoid using hard-coded literals in conditional statements. By declaring them as static variables or private members with descriptive names maintainability is enhanced. By default, the literals “-1” and “0” are ignored. More exceptions can be defined with the property “ignoreMagicNumbers”.


//IfStatement/Expression/*/PrimaryExpression/PrimaryPrefix/Literal
[not(NullLiteral)]
[not(BooleanLiteral)]
[empty(index-of(tokenize($ignoreMagicNumbers, ','), @Image))]

Example(s):


private static final int MAX_NUMBER_OF_REQUESTS = 10;

public void checkRequests() {

    if (i == 10) {                        // magic number, buried in a method
      doSomething();
    }

    if (i == MAX_NUMBER_OF_REQUESTS) {    // preferred approach
      doSomething();
    }

    if (aString.indexOf('.') != -1) {}     // magic number -1, by default ignored
    if (aString.indexOf('.') >= 0) { }     // alternative approach

    if (aDouble > 0.0) {}                  // magic number 0.0
    if (aDouble >= Double.MIN_VALUE) {}    // preferred approach
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy