Skip to content

[java] New Rule: Always compare enum values with == #6193

@adangel

Description

@adangel

Proposed Rule Name: ❓ UnnecessaryEqualsForEnum | EnumComparison

Proposed Category: ❓ Best Practices | Code Style

Description:
See #6116 (comment)

Enum should be compared using ==, this is more readable. Using equals() is not necessary (and is prone to NPE).

Code Sample:

class Foo {
  void method(Thread.State state1, Thread.State state2) {
    if (state1.equals(state2)) { }  // violation

    if (state1 == state2) {}  // correct
  }
}

Possible XPath expression:

//MethodCall[pmd-java:matchesSig("_#equals(java.lang.Object)")]
  [VariableAccess[pmd-java:typeIs("java.lang.Enum")]]
  [ArgumentList[VariableAccess[pmd-java:typeIs("java.lang.Enum")]]]

Possible Properties:

  • none

References:

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:new-ruleProposal to add a new built-in rule

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions