Walter: extend existing classes with new methods?

Kirk McDonald kirklin.mcdonald at gmail.com
Sun Sep 3 12:13:59 PDT 2006


Marcio wrote:
> Bill Baxter wrote:
> 
>> Marcio wrote:
>>
>>> Walter,
>>>
>>>    Do you plan to add the ability of adding methods to an existing 
>>> class, from another module?
>>>
>>>    This ties to the issues raised at 
>>> http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt and the fact 
>>> that some languages/systems have had this capability for years 
>>> (Smalltalk, for example, and more recently Ruby) with very beneficial 
>>> results.
>>>
>>
>> Smalltalk and Ruby are both dynamically typed languages.  D is 
>> statically typed -- that is the type of everything must be known at 
>> compile-time, and in particular what methods are present must be 
>> known.    AFIK, in D, like in C++, someobject.foo() either fails to 
>> compile, or it successully calls foo() at runtime.  There is no 
>> runtime check to see if the method exists or not before calling it.  
>> What you're asking for is a really big fundamental change to what D is.
> 
> 
> 
> No, I am asking for extending at compile-time. Example: You provide me 
> with a library written in D, with full source, and my app can add 
> methods to some of your classes. Then I compile the full source.
> 
> This is quite doable, even in D.
> 
> Adding methods at runtime is an issue if you allow plugins to be loaded 
> from DLLs. If these plugins can add not only classes but also add 
> methods to existing classes, then you need the functionality at runtime.
> 
> I am being modest in my request. Compile-time extension would be 
> straightforward and very useful.
> 
> marcio

There is a problem with this.

class Foo { }

static if (is(typeof(Foo.bar))) {
     const bool has_bar = true;
} else {
     const bool has_bar = false;
}

/+ Add a 'bar' member to Foo somehow +/

Does Foo have a 'bar' member or not? In order for has_bar to be true, 
the compiler would need to arbitrarily look ahead and see if class Foo 
is changed later. This may well be impossible.

If instead you want has_bar to evaluate to false (because the 'bar' 
member hasn't been added at the time the static if is evaluated), then 
this leads to any number of problems. The class is suddenly different at 
different points in the code. In a statically-typed language, this is 
wrong, wrong, wrong.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org



More information about the Digitalmars-d mailing list