Skip to content

Instantly share code, notes, and snippets.

@r00k
Created July 13, 2012 13:58
Show Gist options
  • Save r00k/3105024 to your computer and use it in GitHub Desktop.
Save r00k/3105024 to your computer and use it in GitHub Desktop.
Dependency Injections Pros/Cons/Questions

Dependency Injection

Pros

  • Classes are more modular, as they depend only on the interface of passed-in dependencies. Class behavior can be changed by swapping out a new component.
  • Testing is simplified, since stubs can be substituted for any dependency.

Cons

  • It's harder to understand how a class works when reading just that class. You may have to track down its invocation to see what kind of components are passed in.

Questions:

  • Is DepedencyClass.expects(:new).returns(stub)) a smell, since we should have injected that stub to the class that uses it instead?
  • If a class uses DI, should one only pass in already-instantiated dependencies, or is it okay to let the calling class instantiate them?
  • Am I missing any pros or cons?
@jferris
Copy link

jferris commented Jul 16, 2012

@abernardes All of these abstractions and indirections are tradeoffs, duck typing and dependency injection included. They provide software that is easier to change overall and easier to understand at the unit level, but harder to understand as a whole system. Every class you abstract is another opportunity to name something and create a small, comprehensible unit, but it's also another hop the reader has to make to follow the path of the program. Flat, procedural programming is easy to follow but impossible to change, and the lack of abstractions and naming makes the "what" obvious but the "why" impossible to divine. In short, you need to find the right balance between abstracting yourself into a puzzle and creating a cemented mess of procedural glue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment