The Non-Virtual Interface idiom in D

Jeremie Pelletier jeremiep at gmail.com
Tue Sep 29 07:59:56 PDT 2009


Bill Baxter wrote:
> On Tue, Sep 29, 2009 at 4:04 AM, Don <nospam at nospam.com> wrote:
>> Andrei Alexandrescu wrote:
>>> In this article:
>>>
>>> http://www.gotw.ca/publications/mill18.htm
>>>
>>> Herb Sutter makes a powerful argument that overridable functions
>>> (customization points) should actually not be the same as the publically
>>> available interface. This view rhymes with the Template Method pattern as
>>> well.
>> Ever since I read that earlier this year, I've wondered about this (from the
>> spec):
>>
>> "All non-static non-private non-template member functions are virtual. This
>> may sound inefficient, but since the D compiler knows all of the class
>> hierarchy when generating code, all functions that are not overridden can be
>> optimized to be non-virtual. In fact, since C++ programmers tend to "when in
>> doubt, make it virtual", the D way of "make it virtual unless we can prove
>> it can be made non-virtual" results, on average, in many more direct
>> function calls."
>>
>> Based on what Herb says, D is actively encouraging bad design...
>>
> 
> I don't think that's even true what the spec says.  How can the
> compiler know "all of the class hierarchy" if you compile modules
> separately?  If you compile the base class module first, it has no way
> of knowing whether or not some class in another module is going to
> come along later and want to override a method.  Could be possible in
> a smart linker, I suppose, but the spec clearly says "compiler".
> Walter just got through telling us how the linker is a very simple
> program, so I doubt OPTLINK at least is capable of such feats.
> 
> --bb

The linker basically only resolve symbols, assign addresses and 
generates the executable. It's a pretty straightforward process. Besides 
once the object code gets to the linker, all calls have already been 
compiled in, even if the linker could optimize non-virtual methods the 
calls would still use the vtbl.

I agree that the design can have some flaws by compiling modules 
separately, I would much rather have a virtual AND override keyword 
myself and let the compiler optimize the calls to non-virtuals to skip 
the vtbl lookup.

I don't mind tagging methods with all sorts of keywords like final, 
override, virtual, const, nothrow, pure, etc. I like it that way, gives 
much more meaning to the method by simply looking at its prototype 
(which is often all you're given).



More information about the Digitalmars-d mailing list