How to use PMD in your Java projects

1 minute read

Header

We have seen how to spot bugs in your Java projects by using the SpotBugs plugin [1], but there are other good frameworks out there like PMD [2].

PMD is an extensible static code analyzer which is cross-language, so it can detect bugs for several languages like Apex, JavaScript, XML or Scala [3]. We can even define additional rules in XML [4] to detect new type of bugs or new languages.

PMD has CPD (Copy/Paste Detector) integrated, which is able to detect duplicated code in Java, JSP, C/C++, Kotlin and other languages [5].

Like SpotBugs, PMD can be executed directly on the command line or integrated in your build process as with Gradle, Maven or Ant.

The following is the minimal configuration to add the PMD plugin to the pom.xml file:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-pmd-plugin</artifactId>
  <version>3.13.0</version>
</plugin>

The PMD plugin has four main goals:

  • pmd:pmd: it creates the PMD site report, it can also generate output in CSV, XML or TXT formats
  • pmd:cpd: it analyses the current project to report duplicated code
  • pmd:check: the same as pmd:pmd, but it makes the build failed if it finds any bug
  • pmd:cpd-check: the same as cpd:cpd, but it fails when find duplicated code

Run maven pmd:check to check your project from command line.

To include the PMD’s goal into your Maven pipeline, just add it to any of your phases, typically compile, as we can see here:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-pmd-plugin</artifactId>
    <version>3.13.0</version>
    <configuration>
        <!-- failOnViolation is actually true by default, but can be disabled -->
        <failOnViolation>true</failOnViolation>
        <!-- printFailingErrors is pretty useful -->
        <printFailingErrors>true</printFailingErrors>
    </configuration>
    <executions>
        <execution>
            <phase>verify</phase> <!-- this the default phase -->
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The above is the most basic configuration to use include PMD in your project, but there are many configuration parameters to customize it to use specific rules, JDK versions, etc. In a later post I’ll explain how to implement a progressive strategy to include it in large projects without disrupting builds too much.