IT:AD:Patterns:SOLID/DIP

Summary

The notion that a class declare in its constructor arguments what services it will need, so that they can be instantiated and injected in.

See: http://lostechies.com/derickbailey/2011/09/22/dependency-injection-is-not-the-same-as-the-dependency-inversion-principle/

Constructors are totally under-appreciated things.

A class that has a constructor that has no arguments is … a lier.

It’s basically saying “I’m cool. To do this work, I don’t need anything.” And then somewhere in one of its methods, it goes and instantiates a service that it needs to complete it’s work. It lied.

What it should have said is…“I’m cool to do the work you are asking – but to do it, at some point, I may need the following service. Please instantiate it for me, and pass it to me in my constructor”.

Pay the cost up front – find out if the logger’s config is correctly set up BEFORE you make classes that need it. Etc.

There’s nothing like honesty.

Contrast the following two examples:

     public class PoorObject 
     {

       public void DoSomething (){
         //Current may be null when you go to use it...(A UnitTest would fail for example)
         MembershipProvider.Current.IsAuthenticated();
       }
    }

versus:

    public class BetterObject
    {
        IAuthenticationService _authenticationService;
    
        public SomeObject(IAuthenticationService authenticationService){
          authenticateionService.ValidateIsNotNull("authenticationService");
          _authenticationService = authenticationService;
        }
    
        public void DoSomething(){
         //service is guaranteed to be available at this point:
         _authentication.ValidateIsAuthenticated();
        }
    }