opEquals and the Non-Virtual Interface idiom
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Sun Sep 27 09:26:33 PDT 2009
Here's an article about the perils of equals in Java (opEquals in D):
http://www.ddj.com/article/printableArticle.jhtml;jsessionid=GFKUCQH5S4IHNQE1GHOSKHWATMY32JVN?articleID=184405053&dept_url=/java/
It turns out this is a great example for NVI. In D, we could and should
do the following:
class Object {
// Implement this
private bool opEqualsImpl(Object rhs) {
return false;
}
// Use this
final bool opEquals(Object rhs) {
if (this is rhs) return true;
if (this is null || rhs is null) return false;
return opEqualsImpl(rhs) && rhs.opEqualsImpl(this);
}
}
I took advantage of the fact that in a final function this may be null
without an access violation. The implementation above ensures symmetry
of equality and has each class implement a simpler primitive.
What do you think?
Andrei
More information about the Digitalmars-d
mailing list