Writing clean, maintainable code is a challenging task. Fortunately, there are many patterns, techniques, and reusable solutions available to us to make achieving that task much easier. Dependency Injection is one of those techniques, which is used to write loosely-coupled yet highly-cohesive code.

In this post, we’ll show you how to implement Dependency Injection as you develop an app for plotting historic weather data. After developing the initial app, using Test-Driven Development, you’ll refactor it using Dependency Injection to decouple pieces of the app to make it easier to test, extend, and maintain.

By the end of this post, you should be able to explain what Dependency Injection is and implement it in Python with Test-Driven Development (TDD).

What is Dependency Injection?

In software engineering, Dependency Injection is a technique in which an object receives other objects that it depends on.

  1. It was introduced to manage the complexity of one’s codebase.
  2. It helps simplify testing, extending code, and maintenance.
  3. Most languages that allow for the passing of objects and functions as parameters support it. You hear more about Dependency Injection in Java and C#, though, since it’s difficult to implement. On the other hand, thanks to Python’s dynamic typing along with its duck typing system, it’s easy to implement and thus less noticeable. Django, Django REST Framework, and FastAPI all utilize Dependency Injection.

Benefits:

  1. Methods are easier to test
  2. Dependencies are easier to mock
  3. Tests doesn’t have to change every time that we extend our application
  4. It’s easier to extend the application
  5. It’s easier to maintain the application

For more, refer to Martin Fowler’s Forms of Dependency Injection article.

To see it in action, let’s take a look at a few real-world examples.

Plotting Historic Weather Data

Scenario:

  1. You’ve decided to build an app for drawing plots from weather history data.
  2. You’ve downloaded 2009 temperature by hour data for London.
  3. Your goal is to draw a plot of that data to see how temperature changed over time.

#injection #dependency #python

Python Dependency Injection
2.50 GEEK