Dependency Inversion Principle

High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.

This principle seeks to "invert" the conventional notion that high level modules in software should depend upon the lower level modules. The principle states that high level or low level modules should not depend upon each other, instead they should depend upon abstractions. This is best illustrated by an example.

We will consider the design of a three layer protocol stack. The discussion is divided into three steps:

Original Design

The following code shows the design of a three layered radio link control (RLC) protocol stack. The three layers of the protocol are:

All three layers are modeled as classes. A code skeleton for these classes is presented below. This is not a good design. It has the following limitations:

The solution to these problems is to modify the design of layers by basing it on a common abstraction. This is the subject of the next section.

Layers

Modified Design (Conforms to the Dependency Inversion Principle)

We now apply the Dependency Inversion Principle to the above code. We define an abstract class Protocol_Layer that represents a generic layer. Important elements of the Protocol_Layer abstraction are:

The three layers in the above example, will now inherit from the Protocol_Layer. This design completely decouples the three layers. All the layers depend upon the abstraction but not on each other. The advantages are described in the next section.

Protocol_Layer Abstraction

Advantages of Dependency Inversion

Application of the Dependency Inversion Principle has given us the following advantages:

For more details about the design, please refer to the Protocol Layer Design Pattern article.