Differences

This shows you the differences between two versions of the page.

Link to this comparison view

it:ad:patterns:solid_dip [2019/03/24 12:02] (current)
Line 1: Line 1:
 +# IT:​AD:​Patterns:​SOLID/​DIP #
  
 +
 +
 +<callout type="​Navigation"​ class="​small">​
 +* [[../​|(UP)]]
 +{{indexmenu>​.#​2|nsort tsort}}
 +
 +
 +</​callout>​
 +
 +
 +<panel title="​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/​
 +
 +
 +</​panel>​
 +
 +
 +## DIP ##
 +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:
 +
 +<sxh csharp>
 +     ​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();​
 +       }
 +    }
 +</​sxh>​
 +
 +versus:
 +
 +<sxh csharp>
 +    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();​
 +        }
 +    }
 +</​sxh>​