Delegation (programming) - Language Feature

Language Feature

The short definition is that delegation defines method dispatching the way it is defined for virtual methods in inheritance: It is always the most specific method that is chosen during method-lookup. Hence it is the original receiver entity that is the start of method lookup even though it has passed on control to some other object (through a delegation link, not an object reference). Delegation has the advantage that it can take place at run-time and affect only a subset of entities of some type and can even be removed at run-time. Inheritance on the other hand typically targets the type rather than the instances and is restricted to compile time. On the other hand, inheritance can be statically type-checked while delegation generally cannot without generics (G. Kniesel has shown that a restricted version of delegation can be statically typesafe). Delegation can be termed "run-time inheritance for specific objects".

Example in a C#/Java like language

class A { void foo { // "this" also known under the names "current", "me" and "self" in other languages this.bar; } void bar { print("a.bar"); } }; class B { private A a; // delegation link public B(A a) { this.a = a; } void foo { a.foo; // call foo on the a-instance } void bar { print("b.bar"); } }; a = new A; b = new B(a); // establish delegation between two objects

Calling b.foo will result in a.bar being printed, since class B "delegates" the method foo to a given object of class A.

Programming languages in general do not support delegation as a language concept, but there are a few exceptions, most notably ECMAScript. Self, Kniesels Lava, and the Tcl object system Snit also support delegation. Lava uses an explicit delegation link that can never be null, and can never change during an object's lifetime. Self has the notion of explicit parent slots that can change at run-time. As there were several parent slots, essentially Self has multiple inheritance. As with dual inheritance (described below) this entails a carefully designed method-lookup scheme.

Read more about this topic:  Delegation (programming)

Famous quotes containing the words language and/or feature:

    It is difficult for a woman to define her feelings in language which is chiefly made by men to express theirs.
    Thomas Hardy (1840–1928)

    A snake, with mottles rare,
    Surveyed my chamber floor,
    In feature as the worm before,
    But ringed with power.
    Emily Dickinson (1830–1886)