Comparing apples and oranges
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Sep 29 09:13:04 PDT 2009
Denis Koroskin wrote:
> On Tue, 29 Sep 2009 18:54:28 +0400, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> wrote:
>
>> Consider:
>>
>> class Apple {}
>> class Orange {}
>>
>> void main() {
>> writeln(new Apple == new Orange);
>> }
>>
>> This program always prints "false". By and large, it is odd that one
>> would attempt comparison between unrelated classes. I was thinking, is
>> this ever legitimate, or we should just disallow it statically
>> whenever possible?
>>
>> The comparison would still remain possible by casting to a parent class:
>>
>> writeln(cast(Object) new Apple == cast(Object) new Orange);
>>
>> I could think of rare cases in which one would want two sibling types
>> to compare equal. Consider:
>>
>> class Matrix { ... }
>> // No state added, operations optimized with BLAS
>> class BLASMatrix : Matrix {}
>> // No state added, operations optimized with LAPACK
>> class LAPACKMatrix : Matrix {}
>>
>> Since neither derived class adds any state, both act in comparisons
>> just like the base class Matrix, so it's valid to compare a BLASMatrix
>> with a LAPACKMatrix.
>>
>> How do you think we should go about this? Stay error-prone for the
>> benefit of a few cases, or disallow sibling class comparisons statically?
>>
>>
>> Andrei
>>
>
> I believe Java and C# took bool Object.equals(Object other); way because
> they lacked generics intially and stored all the instances as Objects in
> containers (having equals method in Object allowed them proper ordering
> etc).
>
> D doesn't suffer from that problem and doesn't have to follow the same
> way those languages took.
>
> BTW, nowadays, they define IComparable<T> interface, which is a
> recommended way to implement comparison functions.
>
> That's why I'm all for removing opEquals from Object.
What would you replace it with?
Note that IComparable<T> does not quite solve a lot of the problems, at
least does not make things much easier for the programmer. Comparing
objects is really a double dispatch problem.
Andrei
More information about the Digitalmars-d
mailing list