Rules which enforce generally accepted best practices.
Edit me

AbstractClassWithoutAbstractMethod

Since: PMD 3.0

Priority: Medium (3)

The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation.

This rule is defined by the following XPath expression:

//ClassOrInterfaceDeclaration
 [@Abstract='true'
  and count( .//MethodDeclaration[@Abstract='true'] )=0 ]
  [count(ImplementsList)=0]
  [count(.//ExtendsList)=0]

Example(s):

public abstract class Foo {
  void int method1() { ... }
  void int method2() { ... }
  // consider using abstract methods or removing
  // the abstract modifier and adding protected constructors
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AbstractClassWithoutAbstractMethod" />

AccessorClassGeneration

Since: PMD 1.04

Priority: Medium (3)

Instantiation by way of private constructors from outside of the constructor’s class often causes the generation of an accessor. A factory method, or non-privatization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.AccessorClassGenerationRule

Example(s):

public class Outer {
 void method(){
  Inner ic = new Inner();//Causes generation of accessor class
 }
 public class Inner {
  private Inner(){}
 }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AccessorClassGeneration" />

AccessorMethodGeneration

Since: PMD 5.5.4

Priority: Medium (3)

When accessing a private field / method from another class, the Java compiler will generate a accessor methods with package-private visibility. This adds overhead, and to the dex method count on Android. This situation can be avoided by changing the visibility of the field / method from private to package-private.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.AccessorMethodGenerationRule

Example(s):

public class OuterClass {
    private int counter;
    /* package */ int id;

    public class InnerClass {
        InnerClass() {
            OuterClass.this.counter++; // wrong accessor method will be generated
        }

        public int getOuterClassId() {
            return OuterClass.this.id; // id is package-private, no accessor method needed
        }
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AccessorMethodGeneration" />

ArrayIsStoredDirectly

Since: PMD 2.2

Priority: Medium (3)

Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.ArrayIsStoredDirectlyRule

Example(s):

public class Foo {
    private String [] x;
        public void foo (String [] param) {
        // Don't do this, make a copy of the array at least
        this.x=param;
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ArrayIsStoredDirectly" />

AvoidPrintStackTrace

Since: PMD 3.2

Priority: Medium (3)

Avoid printStackTrace(); use a logger call instead.

This rule is defined by the following XPath expression:

//PrimaryExpression
 [PrimaryPrefix/Name[contains(@Image,'printStackTrace')]]
 [PrimarySuffix[not(boolean(Arguments/ArgumentList/Expression))]]

Example(s):

class Foo {
    void bar() {
        try {
            // do something
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace" />

AvoidReassigningParameters

Since: PMD 1.0

Priority: Medium High (2)

Reassigning values to incoming parameters is not recommended. Use temporary local variables instead.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidReassigningParametersRule

Example(s):

public class Foo {
  private void foo(String bar) {
    bar = "something else";
  }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AvoidReassigningParameters" />

AvoidStringBufferField

Since: PMD 4.2

Priority: Medium (3)

StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes.

This rule is defined by the following XPath expression:

//FieldDeclaration/Type/ReferenceType/ClassOrInterfaceType[@Image = 'StringBuffer' or @Image = 'StringBuilder']

Example(s):

public class Foo {
    private StringBuffer buffer;    // potential memory leak as an instance variable;
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AvoidStringBufferField" />

AvoidUsingHardCodedIP

Since: PMD 4.1

Priority: Medium (3)

Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidUsingHardCodedIPRule

Example(s):

public class Foo {
    private String ip = "127.0.0.1";     // not recommended
}

This rule has the following properties:

Name Default Value Description Multivalued
checkAddressTypes IPv4 | IPv6 | IPv4 mapped IPv6 Check for IP address types. yes. Delimiter is ‘|’.
pattern ^”[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}”$ Regular Expression no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/AvoidUsingHardCodedIP" />

CheckResultSet

Since: PMD 4.1

Priority: Medium (3)

Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. If the value return is ‘false’, it should be handled properly.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.CheckResultSetRule

Example(s):

Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
rst.next();     // what if it returns false? bad form
String firstName = rst.getString(1);

Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
if (rst.next()) {    // result is properly examined and used
    String firstName = rst.getString(1);
    } else  {
        // handle missing data
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/CheckResultSet" />

ConstantsInInterface

Since: PMD 5.5

Priority: Medium (3)

Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums. See Effective Java, item 19.

This rule is defined by the following XPath expression:

//ClassOrInterfaceDeclaration[@Interface='true'][$ignoreIfHasMethods='false' or not(.//MethodDeclaration)]//FieldDeclaration

Example(s):

public interface ConstantInterface {
    public static final int CONST1 = 1; // violation, no fields allowed in interface!
    static final int CONST2 = 1;        // violation, no fields allowed in interface!
    final int CONST3 = 1;               // violation, no fields allowed in interface!
    int CONST4 = 1;                     // violation, no fields allowed in interface!
}

// with ignoreIfHasMethods = false
public interface AnotherConstantInterface {
    public static final int CONST1 = 1; // violation, no fields allowed in interface!

    int anyMethod();
}

// with ignoreIfHasMethods = true
public interface YetAnotherConstantInterface {
    public static final int CONST1 = 1; // no violation

    int anyMethod();
}

This rule has the following properties:

Name Default Value Description Multivalued
ignoreIfHasMethods true Whether to ignore constants in interfaces if the interface defines any methods no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ConstantsInInterface" />

DefaultLabelNotLastInSwitchStmt

Since: PMD 1.5

Priority: Medium (3)

By convention, the default label should be the last label in a switch statement.

This rule is defined by the following XPath expression:

//SwitchStatement
 [not(SwitchLabel[position() = last()][@Default='true'])]
 [SwitchLabel[@Default='true']]

Example(s):

public class Foo {
  void bar(int a) {
   switch (a) {
    case 1:  // do something
       break;
    default:  // the default case should be last, by convention
       break;
    case 2:
       break;
   }
  }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/DefaultLabelNotLastInSwitchStmt" />

ForLoopCanBeForeach

Since: PMD 6.0.0

Priority: Medium (3)

Minimum Language Version: Java 1.5

Reports loops that can be safely replaced with the foreach syntax. The rule considers loops over lists, arrays and iterators. A loop is safe to replace if it only uses the index variable to access an element of the list or array, only has one update statement, and loops through every element of the list or array left to right.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.ForLoopCanBeForeachRule

Example(s):

public class MyClass {
  void loop(List<String> l) {
    for (int i = 0; i < l.size(); i++) { // pre Java 1.5
      System.out.println(l.get(i));
    }

    for (String s : l) {        // post Java 1.5
      System.out.println(s);
    }
  }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach" />

GuardLogStatement

Since: PMD 5.1.0

Priority: Medium High (2)

Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.GuardLogStatementRule

Example(s):

// Add this for performance
    if (log.isDebugEnabled() { ...
        log.debug("log something" + " and " + "concat strings");

This rule has the following properties:

Name Default Value Description Multivalued
guardsMethods isTraceEnabled , isDebugEnabled , isInfoEnabled , isWarnEnabled , isErrorEnabled , isLoggable method use to guard the log statement yes. Delimiter is ‘,’.
logLevels trace , debug , info , warn , error , log , finest , finer , fine , info , warning , severe LogLevels to guard yes. Delimiter is ‘,’.

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/GuardLogStatement" />

JUnit4SuitesShouldUseSuiteAnnotation

Since: PMD 4.0

Priority: Medium (3)

In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation.

This rule is defined by the following XPath expression:

//ClassOrInterfaceBodyDeclaration[MethodDeclaration/MethodDeclarator[@Image='suite']]
[MethodDeclaration/ResultType/Type/ReferenceType/ClassOrInterfaceType[@Image='Test' or @Image = 'junit.framework.Test']]
[not(MethodDeclaration/Block//ClassOrInterfaceType[@Image='JUnit4TestAdapter'])]

Example(s):

public class BadExample extends TestCase{

    public static Test suite(){
        return new Suite();
    }
}

@RunWith(Suite.class)
@SuiteClasses( { TestOne.class, TestTwo.class })
public class GoodTest {
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnit4SuitesShouldUseSuiteAnnotation" />

JUnit4TestShouldUseAfterAnnotation

Since: PMD 4.0

Priority: Medium (3)

In JUnit 3, the tearDown method was used to clean up all data entities required in running tests. JUnit 4 skips the tearDown method and executes all methods annotated with @After after running each test

This rule is defined by the following XPath expression:

//CompilationUnit[not(ImportDeclaration/Name[starts-with(@Image, "org.testng")])]
//ClassOrInterfaceBodyDeclaration[MethodDeclaration/MethodDeclarator[@Image='tearDown']]
[count(Annotation//Name[@Image='After'])=0]

Example(s):

public class MyTest {
    public void tearDown() {
        bad();
    }
}
public class MyTest2 {
    @After public void tearDown() {
        good();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseAfterAnnotation" />

JUnit4TestShouldUseBeforeAnnotation

Since: PMD 4.0

Priority: Medium (3)

In JUnit 3, the setUp method was used to set up all data entities required in running tests. JUnit 4 skips the setUp method and executes all methods annotated with @Before before all tests

This rule is defined by the following XPath expression:

//CompilationUnit[not(ImportDeclaration/Name[starts-with(@Image, "org.testng")])]
//ClassOrInterfaceBodyDeclaration[MethodDeclaration/MethodDeclarator[@Image='setUp']]
[count(Annotation//Name[@Image='Before'])=0]

Example(s):

public class MyTest {
    public void setUp() {
        bad();
    }
}
public class MyTest2 {
    @Before public void setUp() {
        good();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseBeforeAnnotation" />

JUnit4TestShouldUseTestAnnotation

Since: PMD 4.0

Priority: Medium (3)

In JUnit 3, the framework executed all methods which started with the word test as a unit test. In JUnit 4, only methods annotated with the @Test annotation are executed.

This rule is defined by the following XPath expression:

//ClassOrInterfaceDeclaration[
       matches(@Image, $testClassPattern)
        or ExtendsList/ClassOrInterfaceType[pmd-java:typeof(@Image, 'junit.framework.TestCase', 'TestCase')]]

    /ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration[MethodDeclaration[@Public=true()]/MethodDeclarator[starts-with(@Image, 'test')]]
    [not(Annotation//Name[pmd-java:typeof(@Image, 'org.junit.Test', 'Test')])]

Example(s):

public class MyTest {
    public void testBad() {
        doSomething();
    }

    @Test
    public void testGood() {
        doSomething();
    }
}

This rule has the following properties:

Name Default Value Description Multivalued
testClassPattern Test The regex pattern used to identify test classes no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnit4TestShouldUseTestAnnotation" />

JUnitAssertionsShouldIncludeMessage

Since: PMD 1.04

Priority: Medium (3)

JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(), not the two-argument version.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.JUnitAssertionsShouldIncludeMessageRule

Example(s):

public class Foo extends TestCase {
    public void testSomething() {
        assertEquals("foo", "bar");
        // Use the form:
        // assertEquals("Foo does not equals bar", "foo", "bar");
        // instead
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnitAssertionsShouldIncludeMessage" />

JUnitTestContainsTooManyAsserts

Since: PMD 5.0

Priority: Medium (3)

JUnit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness. Consider breaking the test scenario into multiple, shorter test scenarios.
Customize the maximum number of assertions used by this Rule to suit your needs.

This rule is defined by the following XPath expression:

//MethodDeclarator[(@Image[fn:matches(.,'^test')] or ../../Annotation/MarkerAnnotation/Name[@Image='Test']) and count(..//PrimaryPrefix/Name[@Image[fn:matches(.,'^assert')]]) > $maximumAsserts]

Example(s):

public class MyTestCase extends TestCase {
    // Ok
    public void testMyCaseWithOneAssert() {
        boolean myVar = false;
        assertFalse("should be false", myVar);
    }

    // Bad, too many asserts (assuming max=1)
    public void testMyCaseWithMoreAsserts() {
        boolean myVar = false;
        assertFalse("myVar should be false", myVar);
        assertEquals("should equals false", false, myVar);
    }
}

This rule has the following properties:

Name Default Value Description Multivalued
maximumAsserts 1 Maximum number of Asserts in a test method no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnitTestContainsTooManyAsserts" />

JUnitTestsShouldIncludeAssert

Since: PMD 2.0

Priority: Medium (3)

JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.JUnitTestsShouldIncludeAssertRule

Example(s):

public class Foo extends TestCase {
   public void testSomething() {
      Bar b = findBar();
   // This is better than having a NullPointerException
   // assertNotNull("bar not found", b);
   b.work();
   }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnitTestsShouldIncludeAssert" />

JUnitUseExpected

Since: PMD 4.0

Priority: Medium (3)

In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.JUnitUseExpectedRule

Example(s):

public class MyTest {
    @Test
    public void testBad() {
        try {
            doSomething();
            fail("should have thrown an exception");
        } catch (Exception e) {
        }
    }

    @Test(expected=Exception.class)
    public void testGood() {
        doSomething();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/JUnitUseExpected" />

LooseCoupling

Since: PMD 0.7

Priority: Medium (3)

The use of implementation types (i.e., HashSet) as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types (i.e, Set) provides much more flexibility.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.LooseCouplingRule

Example(s):

import java.util.ArrayList;
import java.util.HashSet;

public class Bar {
    // sub-optimal approach
    private ArrayList<SomeType> list = new ArrayList<>();

    public HashSet<SomeType> getFoo() {
        return new HashSet<SomeType>();
    }

    // preferred approach
    private List<SomeType> list = new ArrayList<>();

    public Set<SomeType> getFoo() {
        return new HashSet<SomeType>();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/LooseCoupling" />

MethodReturnsInternalArray

Since: PMD 2.2

Priority: Medium (3)

Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced outside of the object that owns it. It is safer to return a copy of the array.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.MethodReturnsInternalArrayRule

Example(s):

public class SecureSystem {
    UserData [] ud;
    public UserData [] getUserData() {
        // Don't return directly the internal array, return a copy
        return ud;
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/MethodReturnsInternalArray" />

MissingOverride

Since: PMD 6.2.0

Priority: Medium (3)

Minimum Language Version: Java 1.5

Annotating overridden methods with @Override ensures at compile time that the method really overrides one, which helps refactoring and clarifies intent.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.MissingOverrideRule

Example(s):

public class Foo implements Runnable {
                // This method is overridden, and should have an @Override annotation
                public void run() {

                }
            }

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/MissingOverride" />

OneDeclarationPerLine

Since: PMD 5.0

Priority: Medium Low (4)

Java allows the use of several variables declaration of the same type on one line. However, it can lead to quite messy code. This rule looks for several declarations on the same line.

This rule is defined by the following XPath expression:

//LocalVariableDeclaration
   [count(VariableDeclarator) > 1]
   [$strictMode or count(distinct-values(VariableDeclarator/@BeginLine)) != count(VariableDeclarator)]

Example(s):

String name;            // separate declarations
String lastname;

String name, lastname;  // combined declaration, a violation

String name,
       lastname;        // combined declaration on multiple lines, no violation by default.
                        // Set property strictMode to true to mark this as violation.

This rule has the following properties:

Name Default Value Description Multivalued
strictMode false If true, mark combined declaration even if the declarations are on separate lines. no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/OneDeclarationPerLine" />

PositionLiteralsFirstInCaseInsensitiveComparisons

Since: PMD 5.1

Priority: Medium (3)

Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false.

This rule is defined by the following XPath expression:

//PrimaryExpression[
        PrimaryPrefix[Name
                [
    (ends-with(@Image, '.equalsIgnoreCase'))
                ]
        ]
        [
                   (../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal)
    and
    ( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )
        ]
]
[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]
[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]

Example(s):

class Foo {
  boolean bar(String x) {
    return x.equalsIgnoreCase("2"); // should be "2".equalsIgnoreCase(x)
  }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/PositionLiteralsFirstInCaseInsensitiveComparisons" />

PositionLiteralsFirstInComparisons

Since: PMD 3.3

Priority: Medium (3)

Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false.

This rule is defined by the following XPath expression:

//PrimaryExpression[
    PrimaryPrefix[Name[(ends-with(@Image, '.equals'))]]
        [
            (../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral='true'])
            and
            ( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )
        ]
]
[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]
[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]

Example(s):

class Foo {
  boolean bar(String x) {
    return x.equals("2"); // should be "2".equals(x)
  }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/PositionLiteralsFirstInComparisons" />

PreserveStackTrace

Since: PMD 3.7

Priority: Medium (3)

Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost making it difficult to debug effectively.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.PreserveStackTraceRule

Example(s):

public class Foo {
    void good() {
        try{
            Integer.parseInt("a");
        } catch (Exception e) {
            throw new Exception(e); // first possibility to create exception chain
        }
        try {
            Integer.parseInt("a");
        } catch (Exception e) {
            throw (IllegalStateException)new IllegalStateException().initCause(e); // second possibility to create exception chain.
        }
    }
    void bad() {
        try{
            Integer.parseInt("a");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/PreserveStackTrace" />

ReplaceEnumerationWithIterator

Since: PMD 3.4

Priority: Medium (3)

Consider replacing Enumeration usages with the newer java.util.Iterator

This rule is defined by the following XPath expression:

//ImplementsList/ClassOrInterfaceType[@Image='Enumeration']

Example(s):

public class Foo implements Enumeration {
    private int x = 42;
    public boolean hasMoreElements() {
        return true;
    }
    public Object nextElement() {
        return String.valueOf(i++);
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ReplaceEnumerationWithIterator" />

ReplaceHashtableWithMap

Since: PMD 3.4

Priority: Medium (3)

Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.

This rule is defined by the following XPath expression:

//Type/ReferenceType/ClassOrInterfaceType[@Image='Hashtable']

Example(s):

public class Foo {
    void bar() {
        Hashtable h = new Hashtable();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ReplaceHashtableWithMap" />

ReplaceVectorWithList

Since: PMD 3.4

Priority: Medium (3)

Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required.

This rule is defined by the following XPath expression:

//Type/ReferenceType/ClassOrInterfaceType[@Image='Vector']

Example(s):

public class Foo {
    void bar() {
        Vector v = new Vector();
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/ReplaceVectorWithList" />

SwitchStmtsShouldHaveDefault

Since: PMD 1.0

Priority: Medium (3)

All switch statements should include a default option to catch any unspecified values.

This rule is defined by the following XPath expression:

//SwitchStatement[not(SwitchLabel[@Default='true'])]

Example(s):

public void bar() {
    int x = 2;
    switch (x) {
      case 1: int j = 6;
      case 2: int j = 8;
          // missing default: here
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/SwitchStmtsShouldHaveDefault" />

SystemPrintln

Since: PMD 2.1

Priority: Medium High (2)

References to System.(out|err).print are usually intended for debugging purposes and can remain in the codebase even in production code. By using a logger one can enable/disable this behaviour at will (and by priority) and avoid clogging the Standard out log.

This rule is defined by the following XPath expression:

//Name[
    starts-with(@Image, 'System.out.print')
    or
    starts-with(@Image, 'System.err.print')
    ]

Example(s):

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    public void testA () {
        System.out.println("Entering test");
        // Better use this
        log.fine("Entering test");
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/SystemPrintln" />

UnusedFormalParameter

Since: PMD 0.8

Priority: Medium (3)

Avoid passing parameters to methods or constructors without actually referencing them in the method body.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedFormalParameterRule

Example(s):

public class Foo {
    private void bar(String howdy) {
        // howdy is not used
    }
}

This rule has the following properties:

Name Default Value Description Multivalued
checkAll false Check all methods, including non-private ones no

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedFormalParameter" />

UnusedImports

Since: PMD 1.0

Priority: Medium Low (4)

Avoid unused import statements to prevent unwanted dependencies. This rule will also find unused on demand imports, i.e. import com.foo.*.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedImportsRule

Example(s):

import java.io.File;  // not referenced or required
import java.util.*;   // not referenced or required

public class Foo {}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedImports" />

UnusedLocalVariable

Since: PMD 0.1

Priority: Medium (3)

Detects when a local variable is declared and/or assigned, but not used.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedLocalVariableRule

Example(s):

public class Foo {
    public void doSomething() {
        int i = 5; // Unused
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedLocalVariable" />

UnusedPrivateField

Since: PMD 0.1

Priority: Medium (3)

Detects when a private field is declared and/or assigned a value, but not used.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedPrivateFieldRule

Example(s):

public class Something {
    private static int FOO = 2; // Unused
    private int i = 5; // Unused
    private int j = 6;
    public int addOne() {
        return j++;
    }
}

This rule has the following properties:

Name Default Value Description Multivalued
ignoredAnnotations lombok.Setter | lombok.Getter | lombok.Builder | lombok.Data | lombok.RequiredArgsConstructor | lombok.AllArgsConstructor | lombok.Value | lombok.NoArgsConstructor | java.lang.Deprecated | javafx.fxml.FXML Fully qualified names of the annotation types that should be ignored by this rule yes. Delimiter is ‘|’.

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedPrivateField" />

UnusedPrivateMethod

Since: PMD 0.7

Priority: Medium (3)

Unused Private Method detects when a private method is declared but is unused.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UnusedPrivateMethodRule

Example(s):

public class Something {
    private void foo() {} // unused
}

This rule has the following properties:

Name Default Value Description Multivalued
ignoredAnnotations java.lang.Deprecated Fully qualified names of the annotation types that should be ignored by this rule yes. Delimiter is ‘|’.

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod" />

UseAssertEqualsInsteadOfAssertTrue

Since: PMD 3.1

Priority: Medium (3)

This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals.

This rule is defined by the following XPath expression:

//PrimaryExpression[
    PrimaryPrefix/Name[@Image = 'assertTrue']
][
    PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name
    [ends-with(@Image, '.equals')]
]
[ancestor::ClassOrInterfaceDeclaration[//ClassOrInterfaceType[pmd-java:typeof(@Image, 'junit.framework.TestCase','TestCase')] or //MarkerAnnotation/Name[pmd-java:typeof(@Image, 'org.junit.Test', 'Test')]]]

Example(s):

public class FooTest extends TestCase {
    void testCode() {
        Object a, b;
        assertTrue(a.equals(b));                    // bad usage
        assertEquals(?a should equals b?, a, b);    // good usage
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseAssertEqualsInsteadOfAssertTrue" />

UseAssertNullInsteadOfAssertTrue

Since: PMD 3.5

Priority: Medium (3)

This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull.

This rule is defined by the following XPath expression:

//PrimaryExpression[
 PrimaryPrefix/Name[@Image = 'assertTrue' or @Image = 'assertFalse']
][
 PrimarySuffix/Arguments/ArgumentList[
  Expression/EqualityExpression/PrimaryExpression/PrimaryPrefix/Literal/NullLiteral
 ]
]
[ancestor::ClassOrInterfaceDeclaration[//ClassOrInterfaceType[pmd-java:typeof(@Image, 'junit.framework.TestCase','TestCase')] or //MarkerAnnotation/Name[pmd-java:typeof(@Image, 'org.junit.Test', 'Test')]]]

Example(s):

public class FooTest extends TestCase {
    void testCode() {
        Object a = doSomething();
        assertTrue(a==null);    // bad usage
        assertNull(a);          // good usage
        assertTrue(a != null);  // bad usage
        assertNotNull(a);       // good usage
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseAssertNullInsteadOfAssertTrue" />

UseAssertSameInsteadOfAssertTrue

Since: PMD 3.1

Priority: Medium (3)

This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame.

This rule is defined by the following XPath expression:

//PrimaryExpression[
    PrimaryPrefix/Name
     [@Image = 'assertTrue' or @Image = 'assertFalse']
]
[PrimarySuffix/Arguments
 /ArgumentList/Expression
 /EqualityExpression[count(.//NullLiteral) = 0]]
[ancestor::ClassOrInterfaceDeclaration[//ClassOrInterfaceType[pmd-java:typeof(@Image, 'junit.framework.TestCase','TestCase')] or //MarkerAnnotation/Name[pmd-java:typeof(@Image, 'org.junit.Test', 'Test')]]]

Example(s):

public class FooTest extends TestCase {
    void testCode() {
        Object a, b;
        assertTrue(a == b); // bad usage
        assertSame(a, b);   // good usage
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseAssertSameInsteadOfAssertTrue" />

UseAssertTrueInsteadOfAssertEquals

Since: PMD 5.0

Priority: Medium (3)

When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals.

This rule is defined by the following XPath expression:

//PrimaryExpression[PrimaryPrefix/Name[@Image = 'assertEquals']]
[
  PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal/BooleanLiteral
  or
  PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix
  /Name[(@Image = 'Boolean.TRUE' or @Image = 'Boolean.FALSE')]
]

Example(s):

public class MyTestCase extends TestCase {
    public void testMyCase() {
        boolean myVar = true;
        // Ok
        assertTrue("myVar is true", myVar);
        // Bad
        assertEquals("myVar is true", true, myVar);
        // Bad
        assertEquals("myVar is false", false, myVar);
        // Bad
        assertEquals("myVar is true", Boolean.TRUE, myVar);
        // Bad
        assertEquals("myVar is false", Boolean.FALSE, myVar);
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseAssertTrueInsteadOfAssertEquals" />

UseCollectionIsEmpty

Since: PMD 3.9

Priority: Medium (3)

The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.bestpractices.UseCollectionIsEmptyRule

Example(s):

public class Foo {
    void good() {
        List foo = getList();
        if (foo.isEmpty()) {
            // blah
        }
    }

    void bad() {
        List foo = getList();
        if (foo.size() == 0) {
            // blah
        }
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseCollectionIsEmpty" />

UseVarargs

Since: PMD 5.0

Priority: Medium Low (4)

Minimum Language Version: Java 1.5

Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic sugar provides flexibility for users of these methods and constructors, allowing them to avoid having to deal with the creation of an array.

This rule is defined by the following XPath expression:

//FormalParameters/FormalParameter
    [position()=last()]
    [@Array='true']
    [@Varargs='false']
    [not (./Type/ReferenceType[@Array='true'][PrimitiveType[@Image='byte']])]
    [not (./Type/ReferenceType[ClassOrInterfaceType[@Image='Byte']])]
    [not (./Type/PrimitiveType[@Image='byte'])]
    [not (ancestor::MethodDeclaration/preceding-sibling::Annotation/*/Name[@Image='Override'])]
    [not(
        ancestor::MethodDeclaration
            [@Public='true' and @Static='true']
            [child::ResultType[@Void='true']] and
        ancestor::MethodDeclarator[@Image='main'] and
        ..[@ParameterCount='1'] and
        ./Type/ReferenceType[ClassOrInterfaceType[@Image='String']]
    )]

Example(s):

public class Foo {
    public void foo(String s, Object[] args) {
        // Do something here...
    }

    public void bar(String s, Object... args) {
        // Ahh, varargs tastes much better...
    }
}

Use this rule by referencing it:

<rule ref="category/java/bestpractices.xml/UseVarargs" />