www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Idea: Class extension as an interface

I'd like to propose a class extension that allows overriding members. 
What I'm proposing is that:

1. you can create a class extension for a given class you want to 
extend, such an extension
   containing member function definitions which would become available 
to any user of that
   class if he has included the extension's module;
2. functions definitions in the class extension can only access the 
public-accessible members
   of the extended class, package-accessible members if they're in the 
same package, or
   private-accessible memebers if they're in the same module;
3. extensions implicitly create an interface which can be reimplemented 
in a derivative of
   the extended class if the need arise to override some of the 
extension functions.

Calling a non-final extension method would enquire the following 
process: check if the class implements the given extension interface; 
if it does: call from there; if it does not: call the base extension 
method. Making an extension method final means that the function cannot 
be reimplemented by subclasses, allowing us to bypass this process.

Here's a simple example:

~~~~~~
class A {
	string exp;
	string toExpression() { return exp; }
}

// Extension interface for A, providing functions to be used with any A 
descendent
extension Ext : A {
	string toQuotedExpression() { return quote(toExpression()); }
}

// Class B derives from A and reimplements Ext more efficiently.
class B : A, Ext {
	string quotedExp;
	override string toQuotedExpression() { return quotedExp; }
}
~~~~~~

This way, A's implemententor doesn't need to know about any extension 
interfaces applying to A, and A's subclasser can still override any 
extension he wishes, if he has access to it and it makes sense.

Perhaps such extensions could also be defined for structs, typedefs or 
primitive types. In those cases however, functions cannot be overriden.

-- 
Michel Fortin
michel.fortin michelf.com
http://michelf.com/
Jul 01 2008