SSW Foursquare

Do you inject your dependencies?

Last updated by Brady Stroud [SSW] 8 months ago.See history

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 Stephensen
We open source.Loving SSW Rules? Star us on GitHub. Star
Stand by... we're migrating this site to TinaCMS