SOLID Principles: Dependency Inversion Principle (DIP)

Image for post
Image for post
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.
  • components should depend on abstraction.

module need to manage high-level functionality with zero implementation details this allows the module to be used for any type of application and for all modules inside the application.

  • Example:

we have an existing system which sends notifications to users by email

And if we need to send a notification by SMS, we need to change email to SMS in this class, which violates DIP, because the parent class doesn’t depend on abstraction, it has a specific data tie to it.

we can solve it by:

1. create an interface.

2. create classes implements this interface.

3. build class Notification which has Messenger property.

You can replace crate a new object in three ways:

1. Constructor injection:

passing data to Notification Constructor

2. Property injection:

use the setter to set a Property of Notification class

3. Method injection:

pass object data to the method we want to use directly in Notification class

continuo to the rest of SOLID

Written by

Software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store