Dependency Inversion Principle

Aaina jain
Feb 12, 2019 · 2 min read

The dependency inversion principle is a specific form of decoupling software modules. High level modules which provide complex logic should be unaffected by the low level modules which provides utility features. To decouple high level module from low level module, we need to introduce intermediator which is protocol. The principle states:

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

Let’s perform some transactions on user:

As part of transaction, we have to add, delete and update user in database.

Now if there is a requirement to replace current database with other database it shouldn’t affect user transaction operations. At the same time if we have to write test for these operations, it will be hard as we can’t execute tests on real database. There should be low coupling between components used. Let’s decouple this system:

  • DefaultUserTransaction class conforms to UserTransaction protocol and uses DataStore protocol to perform transaction.
  • As part of this implementation, we have segregated data store from user transaction class.

For writing tests of this class, StubDataStore can be injected.

Conclusion: It introduces an protocol abstraction between higher-level and lower-level software components to remove the dependencies between them.

If you like the article, Please clap 👏

You can catch me at:

Linkedin: Aaina Jain

Twitter: __aainajain

Swift India

Swift Developer Community in India 🇮🇳

Aaina jain

Written by

Product Engineer📱at Go-Jek Tech, Organizer & Editor at Swift India

Swift India

Swift Developer Community in India 🇮🇳

More From Medium

More from Swift India

More from Swift India

Functional Swift: Closures { }


More from Swift India

More from Swift India

More from Swift India

Learn about Struct in Swift


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade