Equals

From APIDesign

(Difference between revisions)
Jump to: navigation, search

JaroslavTulach (Talk | contribs)
(New page: Writing equals method in OOP languages can be tricky. The {{JDK|java/lang|Object}}.equals documentation suggest that the relation should be symetric bu...)
Next diff →

Revision as of 08:30, 6 September 2013

Writing equals method in OOP languages can be tricky. The Object.equals documentation suggest that the relation should be symetric but that is hard to enforce. Anyway implementation should at least try. However how should one get ready for subclasses? E.g. make sure instance of following class:

class Date {
  long time; 
 
  public boolean equals(Object o) {
    if (o instanceof Date) {
      return ((Date)o).time == time;
    }
    return false;
  }
}

does not return true when compared to a subclass like:

class Interval extends Date {
  int length; 
}
 
assert !new Date(323).equals(new Interval(323, 10));

One way to do it is to restrict the equals only to own type. E.g.:

public boolean equals(Object o) {
    if (o != null && o.getClass() == Date.class) {
      return ((Date)o).time == time;
    }
    return false;
  }
}

This is approach suitable for algebraic types, but in OOP we might want intervals of length zero to be equal to the Date object with the same beginning. Then it comes to question: Who knows more? (also discussed in SuperVsInner essay). In Java it is safe to assume that subclasses know more - as such it should be the subclass who handles the equals:

class Date {
  long time; 
 
  public boolean equals(Object o) {
    if (o instanceof Date) {
      if (o.getClass() == Date.class) {
        return ((Date)o).time == time;
      } else {
        return o.equals(this);
      }
    }
    return false;
  }
}
 
class Interval extends Date {
  int length; 
 
  public boolean equals(Object o) {
    if (o instanceof Interval) {
      if (o.getClass() == Interval.class) {
        return length == ((Interval)o).length;
      } else {
        return o.equals(this);
      }
    } else {
      return length == 0 && super.equals(o);
    }
  }  
}
 
class SerializableDate extends Date implements java.io.Serializable {
}
 
assert !new Date(323).equals(new Interval(323, 10));
assert new Date(323).equals(new Interval(323, 0));
assert new Date(323).equals(new SerializableDate(323));
Personal tools
buy