Andrew Haley <aph <at> redhat.com> writes:
> No, that's not what I mean by illegal.  It's illegal in the sense that
> the specification places requirements on the implementors of
> subclasses, and that a subclass which does not meet these requirements
> is not a well-defined Java program.

public class Foo {
  private String x;
  public Foo(String x) {
    this.x = x;
  }
  public boolean equals(Object o) {
    if (!(o instanceof Foo)) return false;
    return x.equals(((Foo) o).x);
  }
  public int hashCode() {
    return x.hashCode();
  }
}

This class is clearly intended to meet the spec of equals() and hashCode() and
does so correctly in the vast majority of cases. But not quite: new
Foo("").equals(new Foo(null)) is false, but new Foo(null).equals(new Foo("")) is
NPE.

Is this not a well-defined Java class? Is it illegal? Legal as long as nobody
instantiates it with a null argument, but then suddenly the entire program is
undefined? What if Foo is in a library and the documentation states that x must
not be null, but a bug in the program using that library causes a null argument
to be given by mistake?

I'd argue that there isn't the bright line between "illegal" and "buggy" that
you claim there is. Foo just has a bug - just like Marco's comparator.
Especially since the likely fix would be a check for null in the constructor...

Stuart.


Reply via email to