Home
Do you inject your dependencies?
  v2.0 Posted at 2/11/2012 6:11 PM by Adam Stephensen

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 Figure: Bad Example – A solution where each layer depends on static classes is not maintainable or testable 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 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 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

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.