The Non-Virtual Interface idiom in D

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Sep 27 09:50:36 PDT 2009


Walter Bright wrote:
> Andrei Alexandrescu wrote:
>> This feature would require changing some protection rules, I think for 
>> the better. What do you think?
> 
> 1. what are those changes?

I thought some more about it and here are the changes in protection rules:

1. Public final methods CANNOT be hijacked in derived classes by any 
means. That means, if I see:

class Root {
     final void fun(double) {
         ...
     }
}

I can be darn sure that if I call obj.fun(5) against any class 
inheriting Root, the call will go straight to Root.fun.

One nice thing about that is that we already have very solid 
anti-hijacking rules in place, so we have a great precedence for 
consistency.

2. Private non-final (overridable) methods must be overridable in 
derived classes, even those defined in distinct modules.

3. A class overriding a method is NOT allowed to decrease encapsulation 
by relaxing the protection level of an overridden method. In particular, 
if a method is private and overridable, the function can override it but 
is unable to call super.method.

I think the above rules are enough to implement a mean NVI.

> 2. did you mean to add executable code to an interface?

Yes. We need to allow final methods in interfaces. I remember I posted a 
bug to that effect. These are not problematic to implement because have 
the same binary regime as regular functions:

interface A {
     void transmogrify();
     final void transmogrifyTwice() {
         transmogrify();
         transmogrify();
     }
}

I am very excited about this development, particularly because we can 
get tricky things like opEquals right.


Andrei



More information about the Digitalmars-d mailing list