Jtest logo




Contents  Previous  Next  Index

PB.EQL2


Use 'instanceof' within an 'equals()' method implementation

Description

This rule flags code where an `equals()' method does not use 'instanceof' in the implementation

Allowing only objects of the same class to be considered equal is a clean and simple solution to implementing the 'equals()' method correctly. The 'instanceof' operator checks if the argument is of the correct type or not. Therefore, 'instanceof' can be used to implement the 'equals()' method for an object.

Note: Jtest's PB.EQL rule describes another way to implement the 'equals()' method. Because we have seen arguments for both guidelines, we have included both rules and will allow you to decide which one to use.

Example

 package PB;
 
 public class EQL2 {
     public boolean equals (Object o) {
         super.equals(o);     // violation
     }
 }

Repair

Use 'instanceof' operator before comparing two objects' equality.

 public boolean equal (Object o) {
         if (!(o instanceof EQL2)) 
             return false;
         // ...
     }

Reference

Bloch, Joshua. Effective Java Programming Language Guide. Addison Wesley, 2001, pp 25- 34.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft