Search code examples
javajava-11pmd

Why a PMD violation for unused method when it is obviously used


PMD Failure: ... Rule:UnusedPrivateMethod Priority:3 Avoid unused private methods such as 'printMyString(String)'

private void anyMethod() {
    var myString = "a String";
    printMyString(myString);
}

private void printMyString(String string) {
    System.out.println(string);
}

Using this plugin to maven

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

Solution

  • It appears to be a bug in PMD in that it has an issue following the variable type through the inferred "var". The target method has the parameters specifically defined.

    I can get around this with disabling the specific PMD rule. In the pom.xml I modify the PMD plugin to use a local rule file.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>3.12.0</version>
                <configuration>
                    <linkXRef>false</linkXRef>
                    <printFailingErrors>true</printFailingErrors>
                    <failOnViolation>true</failOnViolation>
                    <rulesets>
                        <ruleset>${basedir}/PMD.xml</ruleset>
                    </rulesets>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                            <goal>cpd-check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    

    And the PMD.xml file (in the root of the project).

    <ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Default Maven PMD Plugin Ruleset" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
        <description>
            Excluding rules.
        </description>
        <rule ref="category/java/bestpractices.xml">
            <exclude name="UnusedPrivateMethod"/>
        </rule>
    </ruleset>