interface function overloading

Stanislav Blinov blinov at loniir.ru
Wed Jan 12 08:26:32 PST 2011


09.01.2011 15:22, %u пишет:
> == Quote from bearophile (bearophileHUGS at lycos.com)'s article
>> %u:
>>>    func(cast(I2)(new C()));
>> That code smells a bit (http://en.wikipedia.org/wiki/Code_smell ).
>> Bye,
>> bearophile
> Extract the construction and you get:
>
> ----
> module main;
>
> interface I1{}
> interface I2 : I1{}
>
> class C : I2{
>    this(){}
> }
>
> void func(I1 i){}
> void func(I2 i){}
>
> void main(){
>    C c = new C();
>    func( cast(I2)c );
> }
> ----
>
> What is the deeper problem in this little snippet?
> Or do you mean there is something wrong if you encounter this pattern.
>
> I don't think it's really that much worse than renaming one(or both) of the funcs.
> It forces you to cast all class:I2 objects to the func you want called, but all
> class:I1 objects already call the correct func.
>
> I think different named funcs is a better solution, but I don't think the cast
> solution exemplifies a pattern of indication to a deeper problem.
>
In C++ I sometimes have similar problems, especially with multiple 
inheritance. Though, as Jonathan mentioned, those problems are even more 
annoying because of hijacking: you don't always immediately notice them.
Long ago I've decided to always employ conversion methods for such 
cases, which in D might look like this:

class C : I2{
   I1 toI1() { return this; }
   I2 toI2() { return this; }
}

This unclutters the code a bit, i think:

void main(){
   func((new C).toI2()); // compare with func(cast(I2)(new C));
   C c = new C;
   func(c.toI1()); // compare with(cast(I1)c);
}

The calls to conversion methods could be even shorter if they were 
properties, because of omitted parens. Anyway, once I stuck to this 
strategy, it never failed me.


More information about the Digitalmars-d-learn mailing list