Delegation (programming)
Encyclopedia
In object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, there are two related notions of delegation.
  • Most commonly, it refers to a programming language feature making use of the method lookup rules for dispatching so-called self-calls as defined by Lieberman in his 1986 paper "Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems". Delegation as a language feature supports the prototype-based programming
    Prototype-based programming
    Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming...

     model.
  • In its original usage, delegation refers to one object relying upon another to provide a specified set of functionalities. In research, this is often referred to as consultation or as aggregation in modeling.
  • In C#, a delegate is a way of telling which method to call when an event is triggered, keeping the method type.


Despite delegation being fairly widespread, relatively few major programming languages implement delegation as an alternative model to static inheritance. The Self
Self programming language
Self is an object-oriented programming language based on the concept of prototypes. Essentially an extreme dialect of Smalltalk, it was used mainly as an experimental test system for language design in the 1980s and 1990s. In 2006, Self was still being developed as part of the Klein project, which...

 programming language incorporates the notion of delegation through its notion of mutable parent slots that are used upon method lookup on self calls.

In object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, a multicast delegate is a delegate that points to several methods. Multicast delegation is a mechanism that provides functionality to execute more than one method. There is a linked-list of delegates maintained internally, and when the multicast delegate is invoked, the list of delegates is executed.

Design pattern

Delegation is the simple yet powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation where one object defers a task to another object, known as the delegate. This mechanism is sometimes referred to as aggregation, consultation or forwarding (when a wrapper object doesn't pass itself to the wrapped object).

Delegation is dependent upon dynamic binding, as it requires that a given method call can invoke different segments of code at runtime. It is used throughout Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

 (and its predecessor NeXTStep
NEXTSTEP
NeXTSTEP was the object-oriented, multitasking operating system developed by NeXT Computer to run on its range of proprietary workstation computers, such as the NeXTcube...

) as a means of customizing the behavior of program components. It enables implementations such as making use of a single OS-provided class to manage windows because the class takes a delegate that is program-specific and can override default behavior as needed. For instance, when the user clicks the close box, the window manager sends the delegate a windowShouldClose: call, and the delegate can delay the closing of the window if there is unsaved data represented by the window's contents.

It has been argued that delegation may in some cases be preferred for inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

 to make program code more readable and understandable.

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
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

. Self
Self programming language
Self is an object-oriented programming language based on the concept of prototypes. Essentially an extreme dialect of Smalltalk, it was used mainly as an experimental test system for language design in the 1980s and 1990s. In 2006, Self was still being developed as part of the Klein project, which...

, Kniesels Lava, and the Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

 object system Snit
Snit
Snit is an object-oriented extension to the Tcl programming language. Snit is a recursive acronym that stands for "Snit's Not Incr Tcl." Snit is a pure Tcl object and megawidget system. It is unique among Tcl object systems in that it is based not on inheritance but on delegation...

 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.

Dual inheritance

If the language supports both delegation and inheritance one can do dual inheritance by utilizing both mechanisms at the same time as in


class C extends A
{
delegationlink D d;
}


This calls for additional rules for method lookup, as there are now potentially two methods that can be denoted as the most specific (due to the two lookup paths). This is elaborated in K. Graversen's Ph.D. thesis on roles.

Related areas

Delegation can be described as a low level mechanism for sharing code and data between entities. Thus it builds the foundation for other language constructs. Notably role-oriented programming
Role-Oriented Programming
Role-oriented programming is a form of computer programming aimed at expressing things in terms which are analogous to human conceptual understanding of the world. This should make programs easier to understand and maintain....

 languages have been utilizing delegation but especially the older ones factually used aggregation while stating the use of delegation. This should not be considered cheating, merely the plural definitions of what delegation means (as described above).

In recent time however work has also been carried out in distributing delegation, so e.g. clients of a search engine (finding cheap hotel rooms) can use a shared entity using delegation to share best hits and general re-usable functionality.

Delegation has also been suggested for advice resolution in aspect-oriented programming
Aspect-oriented programming
In computing, aspect-oriented programming is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns...

 by Ernst and Lorenz in 2003.

Delegation is a fundamental technique used in languages of prototype-based programming
Prototype-based programming
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming...

 (such as JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

).

Method type delegation

In C#, a delegate is a way of telling which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer which is a delegate. Delegates are good because you can notify several methods that an event has occurred, if you so wish.

Examples for delegates in C# follows:

"Singlecast" delegates (C#)


delegate void Notifier(string sender); // Normal method signature with the keyword delegate

Notifier greetMe; // Delegate variable

void HowAreYou(string sender) {
Console.WriteLine("How are you, " + sender + '?');
}

greetMe = new Notifier(HowAreYou);


A delegate variable calls the associated method and is called as follows:


greetMe("Anton"); // calls HowAreYou("Anton") and prints "How are you, Anton?"


Delegate variables are first-class object
First-class object
In programming language design, a first-class citizen , in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable...

s of the form and can be assigned to any matching method, or to the value . They store a method and its receiver without any parameters:


new DelegateType(funnyObj.HowAreYou);


The object can be and omitted. If the method is , it should not be the object (also called an instance in other languages), but the class itself. It should not be , but could be , or .

To call a method with a delegate successfully, the method signature has to match the with the same number of parameters of the same kind with the same type (including return type).

Multicast delegates (C#)

A delegate variable can hold multiple values at the same time:


void HowAreYouToday(string sender) {
Console.WriteLine("How are you today, " + sender + '?');
}

Notifier greetMe;

greetMe = new Notifier(HowAreYou);
greetMe += new Notifier(HowAreYouToday);

greetMe("Alfred"); // "How are you, Alfred?"
// "How are you today, Alfred?"

greetMe -= new Notifier(HowAreYou);

greetMe("Anastasia"); // "How are you today, Anastasia?"


If the multicast delegate is a function or has no parameter, the parameter of the last call is returned.

See also

  • Delegation pattern
    Delegation pattern
    In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a...

  • Adapter pattern
    Adapter pattern
    In computer programming, the adapter pattern is a design pattern that translates one interface for a class into a compatible interface...

  • Delegate (.NET)
    Delegate (.NET)
    A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....

     – Languages using the .NET Framework
    .NET Framework
    The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

     can offer a facility that allows an object to be used to call a method as a form of type-safe function pointer
    Function pointer
    A function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...

    . Such objects are termed delegates, but are not delegates in the sense presented by this article.
  • Hooking
    Hooking
    In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components...

  • Implementation inheritance
  • Inheritance semantics
  • Virtual inheritance
    Virtual inheritance
    Virtual inheritance is a topic of object-oriented programming. It is a kind of inheritance in which the part of the object that belongs to the virtual base class becomes common direct base for the derived class and any next class that derives from it...

  • Wrapper function
    Wrapper function
    A wrapper function is a function in a computer program whose main purpose is to call a second function with little or no additional computation. This is also known as method delegation. Wrapper functions can be used for a number of purposes....


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK