Skip to content

[java] OnlyOneReturn: False positive with equals method #4257

@sarser2048

Description

@sarser2048

Affects PMD Version:
6.51.0+
7.0.0

Rule: OnlyOneReturn

Description:
When used PMD, I found many false positives about the rule OnlyOneReturn. I think we usually have multi return statements in equals method.

For example, the annotation EqualsAndHashCode from lombok usually generate many return statements in equals method. There are also many examples in large java projects, e.g., Spring.

Code Sample demonstrating the issue:

@Override
public boolean equals(Object o) {  // a case generated by the lombok annotation
    if (o == this) return true;
    if (!(o instanceof EqualsAndHashCodeExample)) return false;
    EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (Double.compare(this.score, other.score) != 0) return false;
    if (!Arrays.deepEquals(this.tags, other.tags)) return false;
    return true;
  }

Expected outcome:

PMD reports a violation at line 3, but that's wrong. That's a false positive.

Running PMD through: [Maven]

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions