Design – Dependency Inversion Principle and Hollywood analogy

analogydependency-inversiondesignobject-oriented-design

Often DIP is known as the Hollywood principle: "Don't call us, we'll call you.".

But doesn't always higher level module calls lower level module, whether there is dependency inversion or not?

Then why is DIP called the Hollywood principle?

Am I missing something? Thanks!

Best Answer

A common way of writing OO code is to to have code such as:

void SomeMethod()
{
    SomeClass x = new SomeClass(params...);
    ...
}

or code such as:

void SomeMethod()
{
    SomeClass x = SomeStaticLocator.GetSomeClass();
    ...
}

In both cases, the code is obtaining other parts of the system by "asking" for them.

With dependency injection/dependency inversion, the opposite (inverse) approach is taken:

void SomeMethod(SomeClass x)
{
    ...
}

Rather than the method asking for its dependencies, it is told what they are. This helps to reduce coupling within the system and makes testing a lot simpler. Further improvements are to then design to interfaces, rather than concrete types to further decouple parts of the system:

void SomeMethod(ISomeClass x)
{
    ...
}

Because the method/class is being supplied its dependencies, rather than it needing to request them itself, the terms "tell; don't ask" and "don't call us, we'll call you" are often used to sum up the behaviour of DI.

Related Topic