WRITELOOP

NOTES ON DEPENDENCY INVERSION (THE 'D' ON 'SOLID')

Dependency Inversion can be used to decrease coupling between classes. Here are some notes on a video I recently saw on YouTube to reinforce that.

2022 September 12
  • Dependency Inversion is the “D” on on SOLID - we’ll call it “DI” here for short

  • It is a mechanism to separate the definition of the interface from its’ implementation

  • You can use ABC (Abstract Base Classes) and type hints to leverage this pattern in Python

  • Type hints in Python are useful for developers, to aid on readability (the interpreter does not not leverage that - although mypy can do that)

  • You can leverage DI to eliminate dependencies between 2 classes (decreases coupling)

  • ABC is like a “contract” for a class

  • If you try to use a class that inherits directly from ABC, you’ll get an error (as expected, because that is just a “contract”)

  • You create the interface creating a class that inherits from ABC, and decorating its’ methods with “abstractmethod” (you import both from “abc”). Then, you make the classes that depended on the class inherit from its’ interface class.

  • E.g.: you have a class LightBulb (A) and another EletricPowerSwitch (B). B depends on A, and need to directly call some of A’s methods. We tend to do exactly that, which is the bad practice. Instead, we must create an ABC called Switch (C) - that will be the interface for (A), and make B depend on C and call C’s methods.

NOTE: The original content(s) that inspired this one can be found at:
https://youtu.be/Kv5jhbSkqLE
All copyright and intellectual property of each one belongs to its' original author.