DIP - Dependency Inversion Principle

Robert C. Martin: "The most flexible systems are
those in which source code dependencies refer only to abstractions, not to concretions"
Your higher-level modules shouldn't depend on lower-level code implementation details but on their abstractions instead

In statically typed languages like Java you should depend on interfaces
Interfaces define methods that must be implemented in a concrete class

Python doesn't have formal interfaces but we can make them by using abc - abstract base class module
It gets even better - Python uses duck-tying.

"If it quacks like a duck it's a duck"

That means that instead of depending on class Duck with method quack our higher-level code can depend on any object with quack implemented in the same way

This gives us a lot of flexibility
Let's take a look at the example.

We have SocialMediaPost which can be posted on Twitter

Here comes the problem - our SocialMedia post now depends on Twitter's implementation

If it changes, SocialMediaPost must change.

Our code is not very flexible
Also, if we want to post on Facebook too out code will get even more dependent

Now it's dependent on Twitter and Facebook implementation
We can inverse this dependency.

SocialMediaPost can accept a list of platforms on which to publish

Now it only depends on the publish method.

To put it ducky way - if it publishes the content it's a social media platform.
The same goes for our platforms.

Their publish method depends on "interface" - in our case it's only a verbal agreement

Instead of SocialMediaPost depending on Twitter and Facebook now all of them depend on the interface.
While interfaces change much less frequently than implementations such code is much more flexible

In our case, we could easily add Instagram without touching SocialMediaPost, Twitter, Facebook
Bear in mind that you cannot eliminate all violations of DIP but you can minimize points where it's violated.
You can follow @testdrivenio.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.