Rules

Secret ingredients to quality software

Edit
Info

Do you inject your dependencies?

Created on 19 Oct 2012 | Last updated by Adam Stephensen on 02 Nov 2012 07:11 AM (over 8 years ago)

Injecting your dependency gives you:

  • Loosely coupled classes
  • Increased code reusing
  • Maintainable code
  • Testable methods
  • All dependencies are specified in one place
  • Class dependencies are clearly visible in the constructor

inject bad 1
inject
Figure: Bad Example – A solution where each layer depends on static classes is not maintainable or testable
inject good 1
inject
Figure: Good Example – Dependencies in each layer should only be interfaces. This allows dependencies to be easily interchanged and unit tests to be written against mock/fake objects
inject bad 2
inject
Figure: Bad Example – Classes should not include dependencies on database classes or business objects. Both of these classes may contain dependencies on external services like web services or databases
inject good 2
inject
Figure: Good Example – The dependencies are injected into the class. This enables alternative classes to be injected. For example, a DHLShippingCalculator should be easily substituted for a FedexShippingCalculator. A MockShippingCalculator and MockProductRepository could be injected if we wanted to run unit tests

Adam StephensenAdam Stephensen

We open source. This page is on GitHub