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

Subclasses that add fields should override "equals"

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Override the "equals" method in this class
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      30min
    • Analysis Scope:
      Main Sources
    • FindBugs:
      EQ_DOESNT_OVERRIDE_EQUALS

      Description

      Extend a class that overrides equals and add fields without overriding equals in the subclass, and you run the risk of non-equivalent instances of your subclass being seen as equal, because only the superclass fields will be considered in the equality test.

      This rule looks for classes that do all of the following:

      • extend classes that override equals.
      • do not themselves override equals.
      • add fields.

      Noncompliant Code Example

      public class Fruit {
        private Season ripe;
      
        public boolean equals(Object obj) {
          if (obj == this) {
            return true;
          }
          if (this.class != obj.class) {
            return false;
          }
          Fruit fobj = (Fruit) obj;
          if (ripe.equals(fobj.getRipe()) {
            return true;
          }
          return false;
        }
      }
      
      public class Raspberry extends Fruit {  // Noncompliant; instances will use Fruit's equals method
        private Color ripeColor;
      }
      

      Compliant Solution

      public class Fruit {
        private Season ripe;
      
        public boolean equals(Object obj) {
          if (obj == this) {
            return true;
          }
          if (this.class != obj.class) {
            return false;
          }
          Fruit fobj = (Fruit) obj;
          if (ripe.equals(fobj.getRipe()) {
            return true;
          }
          return false;
        }
      }
      
      public class Raspberry extends Fruit {
        private Color ripeColor;
      
        public boolean equals(Object obj) {
          if (! super.equals(obj)) {
            return false;
          }
          Raspberry fobj = (Raspberry) obj;
          if (ripeColor.equals(fobj.getRipeColor()) {  // added fields are tested
            return true;
          }
          return false;
        }
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                ann.campbell.2 Ann Campbell
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: