The impoliteness of overriding methods

foobar foo at bar.com
Thu Dec 20 11:30:36 PST 2012


On Thursday, 20 December 2012 at 14:51:31 UTC, Dan wrote:
> On Thursday, 20 December 2012 at 07:48:12 UTC, foobar wrote:
>>
>>
>> This is trivially implemented with a simple OO design pattern 
>> in any usual OO language:
>>
>> class Base {
>>  public override precious() {...}
>>  private void myPrecious() {
>>    before();
>>    precious();
>>    after();
>>  }
>> }
>>
>> class Derived {
>>  override precious() {...}
>> }
>>
>> Having syntax sugar is redundant given how simple this pattern 
>> is.
>
> I think it is more than syntactic sugar and in this case it is 
> trivial because you as a designer of Base anticipate only one 
> level of Derived. But, assume there are to be 2, 3, 4, or more 
> levels of derivation. In fact, maybe you don't know how many 
> levels there will be. For a chain of B->D1->D2->D3 I don't see 
> how you can up front get the same effect this way. At the level 
> of D2, base will skip the implementation of precious() in D1. 
> At the level of D3, base will skip the implementation of 
> precious() in D1 and D2, etc. Chaining is lost beyond the first 
> level. It is as if something is done in one direction, you want 
> it done the other and you provide an example that does the 
> reversion as long as there are only two entries. It is not 
> truly a general solution.
>

You misunderstand. It is precisely what the quote bellow says - 
it saves you from coming up with new names. The same pattern can 
be applied multiple times for the multi-derivation case you bring 
up, it's just needs more method names.

To extend my previous example:

class Derived {
   override precious() {
     beforeDerived();
     furtherPrecious();
     afterDerived();
   }
}

class FurtherDerived : Derived {
   void furtherPrecious() {...}
}

Now, we get this call chain:
base.myPrecious() -> Derived.precious() -> 
FurtherDerived.furtherPrecious()
This can be extended ad infinitum.

> From the article: "If you chain more than two levels of 
> subclasses, BETA scales better because you don’t need to keep 
> coming up with new names."
>
> Thanks
> Dan


More information about the Digitalmars-d mailing list