opCmp, opEquals

Steven Schveighoffer schveiguy at yahoo.com
Thu Oct 23 08:23:13 PDT 2008


"Jarrett Billingsley" wrote
> On Thu, Oct 23, 2008 at 11:04 AM, bearophile <bearophileHUGS at lycos.com> 
> wrote:
>> I have a small question regarding OOP design. The signature of opCmp, 
>> opEquals when defined inside classes require a Object argument.
>> So you have to define what to do when the given object can't be cast to 
>> the this class. Here you can see two alternative designs:
>>
>> http://codepad.org/tOHnTObl
>>
>> I think the C1 design is a bad design and the C2 is the right one, but 
>> I'd like to know your opinion.
>>
>> I think Python 2.6+ uses the C1 design, Python3+ uses the C2 design.
>>
>> Someone told me that Java uses a mixed approach: the opEquals returns 
>> false when the cast is not possible, while the cmp throws an exception.
>>
>> Bye,
>> bearophile
>>
>
> I think C2 is the right one as well.

Given that the default implementation just compares references, I think C1 
is correct.

Otherwise you have weird shit like this:

class C3
{
  // no opEquals defined, very common
}

auto c3 = new C3;
auto c2 = new C2(0);

if(c3 == c2) // fails, but does not throw
{
    foo();
}

if (c2 == c3) // throws exception
{
   foo();
}

-Steve 




More information about the Digitalmars-d-learn mailing list