Coding Practice: Dependency Injection

Coding Practice: Why is using “new” a bad thing?
The usage of “new” in a class can be an indicator of tight coupling, which can lead to code that is difficult to test and easily broken by change.

Consider how the PaymentTerms class below is tightly coupled to the PaymentCalculator class below:

public class PaymentTerms
{
   private PaymentCalculator   _calculator;

   public PaymentTerms ()
   {
     _calculator = new PaymentCalculator ();
   }
}

If you later wanted to replace PaymentCalculator with a version of the class that was specific to banks in   one use case and a version of the class that was specific to law firms in another use case, you would have to change the class PaymentTerms as well.

Also, if you want to test PaymentTerms, you are forced to implement PaymentCalculator at the same time   (i.e. there is no way to apply a Mock).

Quote:
“Dependency injection is a technique used in object-oriented programming languages. It promotes loose   coupling of components by passing dependencies to an object, rather than having an object instantiate its own dependencies.”
–            Richard Carr

Application:
One fix for this type of coupling is to apply dependency injection.  By making an IPaymentCalculator   interface that receives its implementation via a constructor argument, the   caller can choose to pass in the specific implementation of PaymentCalculator they want to use given their circumstances.

For example:

public class PaymentTerms
{
   private   IPaymentCalculator _calculator;

   public PaymentTerms (IPaymentCalculator calculator)
   {
      _calculator = calculator;
   }
}

public class BankPaymentCalculator   : IPaymentCalculator
{
   //…
}

Also, please consider that if you find yourself having to pass in a lot of arguments via your constructor   to your class, perhaps your class has too many dependencies.

References:
http://dotnetslackers.com/Community/forums/tightly-coupled-and-loosely-coupled-objects/t/1835.aspx

http://www.blackwasp.co.uk/DependencyInjection.aspx

About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.