25.3. Indirection
Problem Where to assign a responsibility, to avoid direct coupling between two (or more) things? How to de-couple objects so that low coupling is supported and reuse potential remains higher?Solution Assign the responsibility to an intermediate object to mediate between other components or services so that they are not directly coupled.The intermediary creates an indirection between the other components.Examples
TaxCalculatorAdapter
These objects act as intermediaries to the external tax calculators. Via polymorphism, they provide a consistent interface to the inner objects and hide the variations in the external APIs. By adding a level of indirection and adding polymorphism, the adapter objects protect the inner design against variations in the external interfaces (see Figure 25.10).
Figure 25.10. Indirection via the adapter.
[View full size image]
Notice how the external TaxMaster remote service application is modeled in Figure 25.10: It's labeled with the «actor» keyword to indicate it's an external software component to our NextGen system.
PersistentStorage
The Pure Fabrication example of decoupling the Sale from the relational database services through the introduction of a PersistentStorage class is also an example of assigning responsibilities to support Indirection. The PersistentStorage acts as a intermediary between the Sale and the database.Discussion "Most problems in computer science can be solved by another level of indirection" is an old adage with particular relevance to object-oriented designs. [3]
[3] By David Wheeler. Note there is also the counter-adage: "Most problems in performance can be solved by removing another layer of indirection!"
Just as many existing design patterns are specializations of Pure Fabrication, many are also specializations of Indirection. Adapter, Facade, and Observer are examples [GHJV95]. In addition, many Pure Fabrications are generated because of Indirection. The motivation for Indirection is usually Low Coupling; an intermediary is added to decouple other components or services.Benefits
- Lower coupling between components.
Related Patterns and Principles
- Protected Variations
- Low Coupling
- Many GoF patterns, such as Adapter, Bridge, Facade, Observer, and Mediator [GHJV95].
- Many Indirection intermediaries are Pure Fabrications.