DEV Community

Discussion on: Explain dependency injection like I'm five

Collapse
 
dwayne profile image
Dwayne Crooks
import sys

def getc()
  c = sys.stdin.read(1)

  if not c:
    raise Exception('unexpected EOF')

  return c

In the code above I'm implicitly depending on standard input. So standard input is a dependency of the function. Among other things it makes that code harder to test.

The code is okay but one way in which it can be improved is by making the dependency on standard input explicit. Here's how:

import sys

def getc(input=sys.stdin)
  c = input.read(1)

  if not c:
    raise Exception('unexpected EOF')

  return c

Pass the dependency as an argument which makes it explicit. The function now takes a file like object which I defaulted to standard input since that would be the typical use case.

What have we gained? The code is much easier to test and understand because you know what depends on what. It's dependencies are explicit.

Passing your dependencies via arguments to functions is one way to "inject your dependencies", hence the term "dependency injection".

If you want to see how it helps with testing in a real project then you can read these examples from my Python Whitespace interpreter project: