Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4454

"equals" method parameters should not be marked "@Nonnull"

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Remove this non-null annotation.
    • Highlighting:
      Hide

      annotation

      Show
      annotation
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      3min
    • Analysis Scope:
      Main Sources

      Description

      By contract, the equals(Object) method, from java.lang.Object, should accept a null argument. Among all the other cases, the null case is even explicitly detailed in the Object.equals(...) Javadoc, stating "For any non-null reference value x, x.equals(null) should return false."

      Assuming that the argument to equals is always non-null, and enforcing that assumption with an annotation is not only a fundamental violation of the contract of equals, but it is also likely to cause problems in the future as the use of the class evolves over time.

      The rule raises an issue when the equals method is overridden and its parameter annotated with any kind of @Nonnull annotation.

      Noncompliant Code Example

      public boolean equals(@javax.annotation.Nonnull Object obj) { // Noncompliant
        // ...
      }
      

      Compliant Solution

      public boolean equals(Object obj) {
        if (obj == null) {
          return false;
        }
        // ... 
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              michael.gumowski Michael Gumowski
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: