The Non-Virtual Interface idiom in D

Jeremie Pelletier jeremiep at gmail.com
Wed Sep 30 12:21:38 PDT 2009


Jérôme M. Berger wrote:
> Jeremie Pelletier wrote:
>> Jérôme M. Berger wrote:
>>> Michel Fortin wrote:
>>>> I fully support having a way to specify a default implementation for 
>>>> a function in an interface. It might get handy for a few things 
>>>> (like implementing the delegate pattern you see everywhere in 
>>>> Cocoa). But it's a bad replacement for contracts.
>>>>
>>>     Then what's the difference between an interface and an abstract 
>>> class? I thought that the whole point of interfaces was that you 
>>> couldn't have implementations of the methods so that you had no 
>>> problem choosing an implementation when inheriting from multiple 
>>> interfaces.
>>>
>>>         Jerome
>>
>> The interface supports multiple inheritance since it doesn't add to 
>> the vtable of the class using it,
> 
>     ?? The interface adds as much (or as little) to the vtable as 
> another class would. The reason why interfaces support multiple 
> inheritance is that since the interface does not contain the code for 
> any of its methods, there is never any doubt which method should be 
> called even if several ancestors have methods with the same signature. 
> Once you add code to the interface you loose that advantage.

Wrong, the implementation of the interface makes the vtable, the 
interface is only a skeleton for the methods. That interface code would 
only provide a default implementation for the class implementing it, 
which is really useful if you intend to have multiple implementations 
and get some generic code from the interface, unless of using template 
mixins.

>> and its code would be implemented on the classes implementing the 
>> interface, not overridden by subclasses.
> 
>     I don't see how that's different from standard class inheritance. 
> After all there is nothing that forces you to override methods in 
> subclasses if they already have an implementation in the parent class 
> either.
> 
>         Jerome

Yes but you can only extend a single base class, while you may implement 
multiple interfaces, how would you implement generic methods for these 
interfaces under that model? The only way is through template mixins and 
that's not the most convenient method.

Basically interface code would be just like templates that gets mixed in 
the implementing class. You could easily write generic contracts for 
interfaces that way, instead of repeating the same contracts in every 
implementation. It's just another tool to help generic programming.



More information about the Digitalmars-d mailing list