*** Welcome to piglix ***

Forwarding (object-oriented programming)


In object-oriented programming, forwarding means that using a member of an object (either a property or a method) 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, 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.

Forwarding is often confused with delegation; 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 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).

The difference between forwarding and delegation is the binding of the self parameter in the wrappee when called through the wrapper. With delegation, the self parameter is bound to the wrapper, with forwarding it is bound to the wrappee. ... Forwarding is a form of automatic message resending; delegation is a form of inheritance with binding of the parent (superclass) at run time, rather than at compile/link time as with 'normal' inheritance.

For example, given the following code:

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, 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; while forwarding provides stronger encapsulation and avoids these problems; see composition over inheritance.


...
Wikipedia

...