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

"equals(Object obj)" should test argument type

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Add a type test to this method.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources
    • FindBugs:
      BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS

      Description

      Because the equals method takes a generic Object as a parameter, any type of object may be passed to it. The method should not assume it will only be used to test objects of its class type. It must instead check the parameter's type.

      Noncompliant Code Example

      public boolean equals(Object obj) {
        MyClass mc = (MyClass)obj;  // Noncompliant
        // ...
      }
      

      Compliant Solution

      public boolean equals(Object obj) {
        if (obj == null)
          return false;
      
        if (this.getClass() != obj.getClass())
          return false;
        
        MyClass mc = (MyClass)obj; 
        // ...
      }
      

        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: