Delegation (object-oriented programming)
{{Short description|Evaluation and comparison of objects}}
{{Other uses|Delegation (computing)}}
{{Distinguish|Forwarding (object-oriented programming)}}
In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). Delegation can be done explicitly, by passing the responsibilities of the sending object to the receiving object, which can be done in any object-oriented language; or implicitly, by the member lookup rules of the language, which requires language support for the feature. Implicit delegation is the fundamental method for behavior reuse in prototype-based programming, corresponding to inheritance in class-based programming. The best-known languages that support delegation at the language level are Self, which incorporates the notion of delegation through its notion of mutable parent slots that are used upon method lookup on self calls, and JavaScript; see JavaScript delegation.
The term delegation is also used loosely for various other relationships between objects; see delegation (programming) for more. Frequently confused concepts are simply using another object, more precisely referred to as consultation or aggregation; and evaluating a member on one object by evaluating the corresponding member on another object, notably in the context of the receiving object, which is more precisely referred to as forwarding (when a wrapper object doesn't pass itself to the wrapped object).{{sfn|Gamma|Helm|Johnson|Vlissides|1995|loc="Delegation", pp. 20–21}}{{sfn|Beck|1997|loc="Delegation", pp. 64–69}}{{efn|Beck 1997 uses the terms "simple delegation" for when the receiving object does not have access to the sending object, and "self delegation" for when the receiving object does have access to the sending object; in modern language these are "forwarding" and "delegation", as used in this article.}} The delegation pattern is a software design pattern for implementing delegation, though this term is also used loosely for consultation or forwarding.
Overview
This sense of delegation as programming language feature making use of the method lookup rules for dispatching so-called self-calls was defined by Lieberman in his 1986 paper "Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems".
Delegation is dependent upon dynamic binding, as it requires that a given method call can invoke different segments of code at runtime{{Citation needed|date = January 2015}}. It is used throughout macOS (and its predecessor NeXTStep) as a means of customizing the behavior of program components.{{cite web | url=https://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html | title=Cocoa Fundamentals Guide: Delegates and Data Sources | author=Apple |date=2009-08-20 | work=Apple Developer Connection | accessdate=2009-09-11 }} 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.
Delegation can be characterized (and distinguished from forwarding) as late binding of self:
{{cite book |title=Perspectives of Systems Informatics: 5th International Andrei Ershov Memorial Conference, PSI 2003, Akademgorodok, Novosibirsk, Russia, July 9-12, 2003, Revised Papers |chapter=Intersecting Classes and Prototypes |page=[https://books.google.com/books?id=lqL4wL5aSkkC&pg=PA38&dq=delegation 38]}}
{{quote|... messages sent to the {{code|self}} (or {{code|this}}) variable in the parent will "come back" to the object that originally received the message.}}
That is, the {{code|self}} in a method definition in the receiving object is not statically bound to that object at definition time (such as compile time or when the function is attached to an object), but rather at evaluation time, it is bound to the original object.
It has been argued that delegation may in some cases be preferred to inheritance to make program code more readable and understandable.[http://heim.ifi.uio.no/~trygver/2007/readability.pdf]Trygve Reenskaug, Dept. of Informatics, University of Oslo, "The Case for Readable Code" (2007) Despite explicit delegation being fairly widespread, relatively few major programming languages implement delegation as an alternative model to inheritance. The precise relationship between delegation and inheritance is complicated; some authors consider them equivalent, or one a special case of the other.{{cite conference | first=Lynn Andrea | last=Stein | title=Delegation is Inheritance | conference=OOPSLA '87 Conference proceedings on Object-oriented programming systems, languages and applications | pages=138–146 | doi=10.1145/38807.38820 }}
Language support for delegation
In languages that support delegation via method lookup rules, method dispatching is defined 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, by contrast, 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 (although a restricted version of delegation can be statically typesafe{{cite book | chapter-url = https://link.springer.com/ | author = Günter Kniesel | title = ECOOP' 99 — Object-Oriented Programming | volume = 1628 | pages = 351–366 | publisher = Springer | date = 1999-11-19 | archiveurl = https://web.archive.org/web/20150304020026/http://link.springer.com/ | archivedate = 2015-03-04 | quote = This paper proposes object-based inheritance (also known as delegation) as a complement to purely forwarding-based object composition. It presents a typesafe integration of delegation into a class-based object model and shows how it overcomes the problems faced by forwarding-based component interaction, how it supports independent extensibility of components and unanticipated, dynamic component adaptation. | accessdate = 2015-03-04 | doi = 10.1007/3-540-48743-3_16 | series = Lecture Notes in Computer Science | isbn = 978-3-540-66156-6 | chapter = Type-Safe Delegation for Run-Time Component Adaptation | citeseerx = 10.1.1.33.7584 | url-status = bot: unknown }}). Delegation can be termed "run-time inheritance for specific objects."
Here is a pseudocode 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 delegate 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 {{code|b.foo()}} will result in b.bar being printed, since {{code|this}} refers to the original receiver object, {{code|b}}, within the context of {{code|a}}. The resulting ambiguity of {{code|this}} is referred to as object schizophrenia.
Translating the implicit {{code|this}} into an explicit parameter, the call (in {{code|B}}, with {{code|a}} a delegate) {{code|a.foo()}} translates to {{code|A.foo(b)}}, using the type of {{code|a}} for method resolution, but the delegating object {{code|b}} for the {{code|this}} argument.
Using inheritance, the analogous code (using capital letters to emphasize that resolution is based on classes, not objects) is:
class A {
void foo() {
this.bar();
}
void bar() {
print("A.bar");
}
}
class B extends A {
public B() {}
void foo() {
super.foo(); // call foo() of the superclass (A)
}
void bar() {
print("B.bar");
}
}
b = new B();
Calling {{code|b.foo()}} will result in B.bar. In this case, {{code|this}} is unambiguous: there is a single object, {{code|b}}, and {{code|this.bar()}} resolves to the method on the subclass.
Programming languages in general do not support this unusual form of delegation as a language concept, but there are a few exceptions{{Citation needed|date = January 2015}}.
=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).
=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 languages have been utilizing delegation, but especially the older ones factually used aggregation while claiming to use delegation. This should not be considered cheating, merely the plural definitions of what delegation means (as described above).
More recently work has also been done on 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 by Ernst and Lorenz in 2003.
See also
Notes
{{notelist}}
References
{{Reflist|1}}
{{refbegin}}
- {{cite book |first=Henry |last=Lieberman |authorlink=Henry Lieberman |chapter=Using prototypical objects to implement shared behavior in object-oriented systems |title=Conference proceedings on Object-oriented programming systems, languages and applications |journal=ACM SIGPLAN Notices |volume=21 |issue=11 |location=Portland |year=1986 |pages=214–223 |chapter-url=http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html|doi=10.1145/960112.28718 |citeseerx=10.1.1.48.69 }}
- Lynn Andrea Stein, Henry Liberman, David Ungar: A shared view of sharing: The Treaty of Orlando. In: Won Kim, Frederick H. Lochovsky (Eds.): Object-Oriented Concepts, Databases, and Applications ACM Press, New York 1989, ch. 3, pp. 31–48 {{ISBN|0-201-14410-7}} (online at [http://citeseer.ist.psu.edu/stein89shared.html Citeseer])
- {{cite book
| first = Erich
| last = Gamma
| authorlink = Erich Gamma
| authorlink2 = Richard Helm | first2 = Richard | last2 = Helm
| authorlink3 = Ralph Johnson (computer scientist) | first3 = Ralph | last3 = Johnson
| authorlink4 = John Vlissides | first4 = John | last4 = Vlissides
| year = 1995
| title = Design Patterns: Elements of Reusable Object-Oriented Software
| publisher = Addison-Wesley
| isbn = 978-0-201-63361-0
| title-link = Design Patterns (book)
}}
- Malenfant, J.: On the Semantic Diversity of Delegation-Based Programming Languages, Proceedings of the OOPSLA95, New York: ACM 1995, pp. 215–230.
- {{cite book
| first = Kent
| last = Beck
| authorlink = Kent Beck
| year = 1997
| title = Smalltalk Best Practice Patterns
| publisher = Prentice Hall
| isbn = 978-0134769042
}}
- Kasper Bilsted Graversen: The nature of roles---A taxonomic analysis of roles as a language construct. Ph.D. Thesis 2006, (Online at [https://web.archive.org/web/20120329110415/http://www.it-c.dk/people/kbilsted/graversen06thesis.pdf IT University of Copenhagen])
{{Refend}}
External links
- [https://web.archive.org/web/20070916214628/http://www.codeproject.com/cpp/CppDelegateImplementation.asp A new way to implement Delegate in C++]
- [https://web.archive.org/web/20070701084227/http://www.codeproject.com/cpp/FastDelegate.asp Fast delegates in C++]
- [http://perfectjpattern.sourceforge.net/delegates.html PerfectJPattern Open Source Project], Provides a reusable implementation of Delegates in Java