Hadi Hariri

Sponsors

The Lounge

Wicked Cool Jobs

Syndication

It’s all about the delivery


The Dependency Inversion Principle states:

 

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.


(Source WikiPedia).

 

Throw that at a terrible programmer, and all you’ll get is a terrible programmer that is annoyed and hates you. So true!

Take the following method:

        public void PrintHelloMessage()
        {
            Console.WriteLine("Hello");
        }

Now ask a developer to add a new method to print the message ‘Goodbye’. Do you think he would do:

        public void PrintGoodbyeMessage()
{
Console.WriteLine("Goodbye");
}


or:

        public void PrintMessage(string message)
{
Console.WriteLine(message);
}

Most likely, he’d do the latter. Why? Because he realizes he’s gaining a benefit by passing a parameter to a method. He knows that if tomorrow you ask him for a “Good Afternoon” message, he won’t have to write a new method.

What is Dependency Injection? It’s one way of complying with the Dependency Inversion Principle. However, when you think about it, what does it boil down to? Passing a parameter to a method, which happens to be a constructor. It seems simple enough doesn’t it? Yet, it’s hard for people to understand it. Why? because they don’t see the value in it.

Explaining a principle to someone without them understanding the benefits and values they get out of it is useless, and that is why concepts such as Dependency Injection or Inversion of Control seem overly complex to the vast majority of developers (believe it or not, those of us that use these things are still a very big minority). It’s complex because they haven’t been explained the values of it. They’ve just been thrown some definition and they are expected to understand that it’s bad for one class to create an instance of another class it uses.

Present a developer with the following code:

    public class AuthServices
    {
        public void AuthUser(string username, string password)
        {
            var authDAL = new AuthDAL();
 
            var user = authDAL.GetUserByUsername(username);
 
            if (user != null)
            {
                if ...
            }
 
        }
    }

and ask them how they’d go about testing this code without having access to a database. Ask them how they’d go about changing AuthDAL for some fake DAL that doesn’t really connect to a database.

They’ll probably come up with the solution of passing the AuthDAL class in as a parameter, and eventually realizing that multiple methods will use the same class, they’ll pass it in via the constructor and set it as an instance field. As long as their AuthDAL has virtual methods, they can create any fake DAL that overrides those methods and returns some dummy value. They might argue that they don’t want virtual methods. And that’s fine. Tell them to define the parameter as an interface. In fact, they probably have already heard of a principle that says that you should program to an interface and not a class. They’ll eventually end up with this code:

  public class AuthServices
{
IAuthDAL authDAL;

public AuthServices(IAuthDAL authDAL)
{
_authDAL = authDAL;
}

public void AuthUser(string username, string password)
{
var user = _authDAL.GetUserByUsername(username);

if (user != null)
{
if ...
}

}
}

 

And voila! You have Dependency Injection via Constructor.

Once they *get* that, then explain to them other benefits, you know the real benefits they get from doing this: decoupled code, easy maintenance, promotion of SRP, etc.  and then throw the principle in their face:

 

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

 

And they’ll see how it all makes sense.

It’s not about throwing or not throwing books. It’s about showing people how something can help them, how they get value of it.


Posted 10-29-2009 10:32 PM by Hadi Hariri
Filed under:

[Advertisement]

Comments

Ryan Rivest wrote re: It’s all about the delivery
on 10-29-2009 6:20 PM

Great post - one of the few explanations of DI that I've seen that is clear without the stilted jibber-jabber.

I think part of the problem is that the developers who are using DI, and other ALT.NET-ish techniques have gotten quite good with them, and forget how it felt when they were learning.

I know I'm guilty of this behavior sometimes.  When I've been using a tool or technique for any extended period of time, and have become accustomed to it, I forget how it was before.  We get so excited about these things that we forget to explain them, or get frustrated when someone doesn't get it.

Sometimes we just have to go back to basic and explain the fundamentals with some examples.

Alexey wrote re: It’s all about the delivery
on 10-29-2009 6:48 PM

Good article, thanks.

BTW the correct spelling is "voila"

Hadi Hariri wrote re: It’s all about the delivery
on 10-30-2009 2:13 AM

@Alexey,

Typo. Corrected. Thanks.

Vitaly Stakhov wrote re: It’s all about the delivery
on 10-30-2009 3:00 AM

Agreed. I would abstract the idea of the post to something like 'always start with the problem'. And oh, the problem should be clear for explaynee.

Richard Dingwall wrote re: It’s all about the delivery
on 10-30-2009 6:23 PM

"They’ll probably come up with the solution of passing the AuthDAL class in as a parameter..."

They also might just add an IsTestMode property to AuthSerivces and throw IFs everywhere.

Just saying ;)

Hadi Hariri wrote re: It’s all about the delivery
on 10-31-2009 2:11 AM

@Richard,

You are absolutely correct. And some do come up with that, but in general developers also realize the problems associated with that solution. Once they think about the IsTestMode property is where they realize, hey, why not just pass what I use instead.

[I'm basing the previous on my own experience of teaching these concepts to people]

Code Monkey Labs wrote Weekly Web Nuggets #81
on 11-24-2009 10:51 AM

Pick of the week: Figuring Out What Your Company Is All About General Hello Tekpub : Rob Conery announces TekPub.com , a new site he's launched with James Avery providing screencasts with content provided by the topic experts themselves. WPF 4 (VS 2010

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco <-- NEW Friend!
NServiceBus <-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)