Friday, April 20, 2012

Disambiguation: Dependency Injection vs. Avoidance of Globals

Dependency injection is about decoupling code. When you avoid the use of globals by passing arguments you are decoupling code. You are removing the dependency the code has on the globals.

You can generalize this decoupling to more than just the avoidance of globals. Take the following code:

def foo(arg):
   return ClassBar(arg).attr


The function foo is dependent on or tightly coupled to ClassBar. The reason this is not good is you will be forced to update foo when:
  • the arguments to ClassBar constructor changes
  • you want to change the creation of a ClassBar object to something else
  • another piece of code wants to access attr from a different object
If the code was rewritten:

def foo(instanceBar):
   return instanceBar.attr


You've pushed the coupling up to the caller. This removed the dependency from the definition of foo. This frees you from having to update foo in the cases outlined above. The more of your code that is decoupled, the fewer code changes you'll need to make.