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

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

Go to download

Sanity4J was created to simplify running multiple static code analysis tools on the Java projects. It provides a single entry point to run all the selected tools and produce a consolidated report, which presents all findings in an easily accessible manner.

There is a newer version: 1.8.2
Show newest version


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