Simply put, the Dependency Inversion Principle is a principle of object oriented programming that states:

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

Since it is fairly well-agreed that a good program or procedure is flexible (not dependent on other programs or procedures), robust (able to be changed or amplified without breaking other parts reliant on it) and reusable (able to be reused with other programs or procedures as necessary).

The common example is a simple program that reads in keyboard input and prints it out to a printer. Initially, code might look something like this:

void Copy()
int c;
while ((c = ReadKeyboard()) != EOF)

This snippet makes use of ReadKeyboard() and WritePrinter() subroutines located elsewhere. These two parts are presumably reusable with other parts of the program, and are therefore well-designed. However, the Copy() program itself suffers because it can only be used with a keyboard and a printer. No other input or output devices can utilize this function. Thus it is immobile.

The solution to this, is to create an abstract Reader() class and an abstract Writer() class for the program to use. You would then feed in your object instances (the keyboard and printer, in this case) into their respective classes, and the Copy() program has now become mobile and flexible.

This is at the heart of the dependency inversion principle. Essentially, all modules should be abstractions and then defined only when the actual running of the program takes place. None of these instances should be built-in to the abstractions - after all, they're called abstractions for a reason!

The principle gets its name because, unlike traditional programming where smaller modules are then assembled into larger modules until the full program is written, here the higher level modules are abstracted into lower level modules, which are abstracted into classes. Thus, the programming hierarchy has been inverted, so to speak.

For more reading on the DIP, check out