September 10, 2018

Dependency Injection

I'm penning this as I sometimes need a quick reference to give people on what "dependency injection" means.

This is most easily done through examples.

The problem

How do you make sure that we don't create this connection? One way would be to switch on environment status, or something similar

def run(test=false):
    if not test:
        self.connection = create_connection

This approach is bad for a few reasons

Inject instead!

def run(connection):
    self.connection = connection

Now, we can pass in whatever connection we like from our testing classes, and pass in the argument "one level up". The logic is the same, but the point where the parameter is created has shifted upwards.

And that's it!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket