2

I use PMD plugin in my Maven project to verify code violations and standards. In Java-8, the PMD complains the below code as Potential violation of Law of Demeter.

Arrays.asList(1, 2, 3, 4).stream().filter(n -> n % 2 == 0).collect(Collectors.toList());

Also the Optional.ofNullable(value).orElse("another"), and almost all lambda expressions.

However, I have set the below PMD property in the pom.xml

<targetJdk>1.8</targetJdk>
<rulesets>
    <ruleset>/category/java/bestpractices.xml</ruleset>
    <ruleset>/category/java/design.xml</ruleset>
    <!-- <ruleset>/category/java/codestyle.xml</ruleset> -->
    <ruleset>/category/java/errorprone.xml</ruleset>
    <ruleset>/category/java/security.xml</ruleset>
    <ruleset>/category/java/multithreading.xml</ruleset>
    <ruleset>/category/java/performance.xml</ruleset>
</rulesets>

Did I miss anything in configuration? Any fixes you can propose?

Eran
  • 387,369
  • 54
  • 702
  • 768
vvra
  • 2,832
  • 5
  • 38
  • 82

1 Answers1

3

The rule flags any usage of objects not created locally / received as parameters.

That automatically means all factory methods are flagged (Arrays.asList, Optional.ofNullable, etc.).

You should either remove the rule from your ruleset (you would need to define your own ruleset xml), or deal with the false positives and suppress them either case by case or customize the rule's suppression (which also need you to define your own ruleset)

Johnco
  • 4,037
  • 4
  • 34
  • 43
  • Surprised the PMD doesn't have ruleset to verify the Java-8? Aren't there any customized (opensource) Java-8 Lambda ruleset you can point me to? – vvra Dec 17 '18 at 05:39
  • PMD **does** handle lambdas, and is very aware of them (actually PMD support up to java 11). This particular rule just doesn't like factory methods, no problem with lambdas themselves. – Johnco Dec 17 '18 at 05:49
  • See https://github.com/pmd/pmd/issues/2160. – Leponzo Nov 07 '21 at 06:21