[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: the benefits of immutability
Michael St . Hippolyte wrote:
> > It is non-trivial to write an externally facing class that allows
> > subclassing.
>
> I'm not sure your example proves this.
You're right. It merely serves to *illustrate* rather than prove.
> Equality in Java is inherently non-transitive regardless of
> subclassing, because if a and b are objects belonging to different
> classes then a.equals(b) and b.equals(a) are in general calls to two
> separate methods that don't necessarily have anything to do with
> each other.
I am not sure I understand what you mean by "inherently
non-transitive". You cannot possibly mean that no "equals" method can
ever be guaranteed transitive, for surely it can. The following
"equals" method is reflexive, symmetric, and transitive.
public final class Circle {
private int m_radius;
public Circle(int radius) {
m_radius = radius;
}
public boolean equals(Object obj) {
if ( ! (obj instanceof Circle) ) { return false; }
return ((Circle) obj).m_radius == m_radius;
}
public int hashCode() {
return m_radius;
}
}
If you meant to say that equality comparison across proper class
boundaries can be fragile, even if both objects share a common
supertype, that would be hard to argue with. That's not a problem
with Java though -- that's a problem with OOP in general.
> Apart from the admittedly broken equality model in Java
See above. It's not just Java.
> what precisely are the difficulties in subclassing an externally
> facing class?
Have you read the example I cited earlier:
http://courses.dce.harvard.edu/~cscie160/EffectiveJava.htm
You don't have to read the entire thing. Scroll down to
InstrumentedHashSet. If you don't find that example convincing,
please post and share your counterarguments.