views:

77

answers:

3

I wonder if it would be possible to insert classes in an inheritance tree at arbitrary positions.

Example:

class Base
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base");
    }
}

class D1:Base
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("D1");
    }
}

class D2:Base
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("D2");
    }
}

class D3:Base
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("D3");
    }
}

Imagine the above classes are from a library with no source available. If I want to modify the behaviour of all the derived classes I have to inherit from all of them and implement the same thing multiple times. Then I have to change all types to my newly derived one. An easier way would be to insert a class directly after Base and somehow (that is probably a big somehow) make the derived class point to that as their base object. The derived classes could then be used unchanged.

class Inserted : after Base
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("Inserted");
    }
}

or

class Inserted : before D1
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("Inserted");
    }
}

The keywords "before" and "after" would control where exactly the class is to be inserted.

In the past I worked with a system that would support something like this and it was a huge productivity boost.

Is this principially possible with for instance, the .Net CLR or with the Java Runtime? Would it be possible to change the v_table to point to the new base class? Why does no modern system support this? What would the ramifications be regarding reliability, security and so on?

+1  A: 

The guys from JRebel are unable to deal with changes in the type hierarchy on the JVM and since it is their core competency I conclude it is very near impossible.

However I think that most things you would like to do can be done using Aspect Oriented Programming and AspectJ.

Peter Tillemans
+1 - AOP: Exactly right.
duffymo
A: 

Are you looking for the decorator pattern when you say "modifying behaviour"?

Abhijeet Kashnia
No, I want to be able to insert classes in the inheritance structure. For instance System.Windows.Forms.Control is the base class for nearly all GUI-elements in .Net. Now I derive a class "Insertee" from Control override the OnMouseClick() method and want all subclasses of Control to point to "Insertee" as their base class. I could then handle the mouseclicks for every type of control with minimal effort.
A: 

This can not be done in .NET and Java. Can you tell what system supports that?

watbywbarif