Decrease coupling in Python code

September 14, 2022

Link:

Overview:

  • Avoid deep inheritance relationships
  • Separate creating resources from using them
    • dependency injection
  • Introduce abstractions
    • dependency inversion
    • reduce the number of dependencies on your code (easier to use and)
  • Avoid inappropriate intimacy
    • Law of Demeter - wiki
    • an object receives more information than it needs
  • Introduce an intermediate data structure
    • adds common interface and splits responsibility
    • one team produces the data structure as output, another team uses the data structure as input

Dependency injection vs dependency inversion:

  • dependency injection separates creation of an object from usage of an object
    • an object is provided to any other object that needs to use it (it is passed in as a parameter)
  • dependency inversion introduces an abstraction for an object
    • objects that use this abstraction no longer depend on the dependency itself
    • high level modules should not depend on low level modules
      • both should depend on abstractions
      • abstractions should not depend on details, details should depend upon abstractions
    • High-level modules, which provide complex logic, should be easily reusable and unaffected by changes in low-level modules, which provide utility features. To achieve that, you need to introduce an abstraction that decouples the high-level and low-level modules from each other.
  • an example
    • you may have a function that sends emails (and this requires an SMTP connection)
      • without dependency injection or inversion
        • the function will create the SMTP object and then send the message
      • with dependency injection
        • the function will receive an SMTP object as a parameter and then send the message
      • with dependency inversion
        • the function will receive an SMTP abstraction (where the implementation can change between testing / dev / prod)
    • an email client could create an smtp server within it