Forwarding (object-oriented programming)
   HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, forwarding means that using a member of an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
(either a
property Property is a system of rights that gives people legal control of valuable things, and also refers to the valuable things themselves. Depending on the nature of the property, an owner of property may have the right to consume, alter, share, r ...
or a
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
) results in actually using the corresponding member of a different object: the use is ''forwarded'' to another object. Forwarding is used in a number of
design patterns ''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a forewo ...
, where some members are forwarded to another object, while others are handled by the directly used object. The forwarding object is frequently called a wrapper object, and explicit forwarding members are called wrapper functions.


Delegation

Forwarding is often confused with
delegation Delegation is the assignment of authority to another person (normally from a manager to a subordinate) to carry out specific activities. It is the process of distributing and entrusting work to another person,Schermerhorn, J., Davidson, P., Poole ...
; formally, they are complementary concepts. In both cases, there are two objects, and the first (sending, wrapper) object uses the second (receiving, wrappee) object, for example to call a method. They differ in what
self The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhoo ...
refers to on the receiving object (formally, in the evaluation environment of the method on the receiving object): in delegation it refers to the sending object, while in forwarding it refers to the receiving object. Note that self is often used implicitly as part of dynamic dispatch (method resolution: which function a method name refers to). For example, given the following code: // Sender void n() // Receiver void m() void n() under delegation this will output m2, n1 because n() is evaluated in the context of the original (sending) object, while under forwarding this will output m2, n2 because n() is evaluated in the context of the receiving object. In casual use, forwarding is often referred to as "delegation", or considered a form of delegation, but in careful usage they are clearly distinguished by what self refers to. While delegation is analogous to
inheritance Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Of ...
, allowing behavioral reuse (and concretely code reuse) ''without'' changing evaluation context, forwarding is analogous to composition, as execution depends only on the receiving (member) object, not the (original) sending object. In both cases, reuse is dynamic, meaning determined at run time (based on the ''object'' to which use is delegated or forwarded), rather than static, meaning determined at compile/link time (based on the ''class'' which is inherited from). Like inheritance, delegation allows the sending object to modify the original behavior, but is susceptible to problems analogous to the
fragile base class The fragile base class problem is a fundamental architectural problem of object-oriented programming systems where base classes ( superclasses) are considered "fragile" because seemingly safe modifications to a base class, when inherited by the ...
; while forwarding provides stronger encapsulation and avoids these problems; see
composition over inheritance Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes th ...
.


Examples

A simple example of explicit forwarding in Java: an instance of B forwards calls to the foo method of its a field: class B Note that when executing a.foo(), the this object is a (a subtype of A), not the original object (an instance of B). Further, a need not be an instance of A: it may be an instance of a subtype. Indeed, A need not even be a class: it may be an interface/
protocol Protocol may refer to: Sociology and politics * Protocol (politics), a formal agreement between nation states * Protocol (diplomacy), the etiquette of diplomacy and affairs of state * Etiquette, a code of personal behavior Science and technology ...
. Contrast with inheritance, in which foo is defined in a superclass A (which must be a class, not an interface), and when called on an instance of a subclass B, it uses the code defined in A, but the this object is still an instance of B: class A class B extends A In this Python example, class B forwards the foo method and the x property to the object in its a field: using these on b (an instance of B) is the same as using them on b.a (the instance of A to which these are forwarded). class A: def __init__(self, x) -> None: self.x = x def foo(self): print(self.x) class B: def __init__(self, a) -> None: self.a = a def foo(self): self.a.foo() @property def x(self): return self.a.x @x.setter def x(self, x): self.a.x = x @x.deleter def x(self): del self.a.x a = A(42) b = B(a) b.foo() # Prints '42'. b.x # Has value '42' b.x = 17 # b.a.x now has value 17 del b.x # Deletes b.a.x.


Simple

In this
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
example, the
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
has a method. This print method, rather than performing the print itself, forwards to an object of class . To the outside world it appears that the object is doing the print, but the object is the one actually doing the work. Forwarding is simply passing a duty off to someone/something else. Here is a simple example: class RealPrinter class Printer public class Main


Complex

The more complex case is a
Decorator Pattern In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often ...
that by using
interfaces Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
, forwarding can be made more flexible and typesafe. "Flexibility" here means that need not refer to or in any way, as the switching of forwarding is abstracted from . In this example, class can forward to any class that implements an interface . Class has a method to switch to another forwarder. Including the clauses improves
type safety In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that i ...
, because each class must implement the methods in the interface. The main tradeoff is more code. interface I class A implements I class B implements I // changing the implementing object in run-time (normally done in compile time) class C implements I public class Main


Applications

Forwarding is used in many design patterns. Forwarding is used directly in several patterns: *
Chain-of-responsibility pattern In object-oriented design, the chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command ob ...
*
Decorator pattern In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often ...
: decorator object adds its own members, forwarding others to the decorated object. *
Proxy pattern In computer programming, the proxy pattern is a software design pattern. A ''proxy'', in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in ...
: proxy object forwards member use to real object. Forwarding may be used in other patterns, but often use is modified; for example, a method call on one object results in several different methods being called on another: *
Adapter pattern In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface. It is often ...
*
Bridge pattern The bridge pattern is a design pattern used in software engineering that is meant to ''"decouple an abstraction from its implementation so that the two can vary independently"'', introduced by the Gang of Four. The ''bridge'' uses encapsulation, a ...
*
Facade pattern The facade pattern (also spelled ''façade'') is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex und ...


References

{{reflist Object-oriented programming Articles with example Java code