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

"equals" methods should work for subclasses

    Details

    • Type: Finding Detection
    • Status: Closed
    • Resolution: Won't Fix
    • Labels:
    • Message:
      Compare "xxx.class" to "this.class" instead.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Targeted languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • FindBugs:
      EQ_GETCLASS_AND_CLASS_CONSTANT

      Description

      Non final classes shouldn't use a hardcoded class name in the equals method. Doing so breaks the method for subclasses. Instead, make the comparison dynamic.

      Noncompliant Code Example

       
      public class Fruit { 
        private Season ripe; 
      
        public boolean equals(Object obj) { 
          if (obj == this) { 
            return true; 
          } 
          if (Fruit.class == obj.class) { // Noncompliant 
            return false; 
          } 
          // ... 
      

      Compliant Solution

       
      public class Fruit { 
        private Season ripe; 
      
        public boolean equals(Object obj) { 
          if (obj == this) { 
            return true; 
          } 
          if (this.class == obj.class) { // will work for subclasses too 
            return false; 
          } 
          // ... 
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                • Created:
                  Updated:
                  Resolved: