Correctly use dependency injection

Posted by Rune on Stack Overflow See other posts from Stack Overflow or by Rune
Published on 2010-04-04T02:34:41Z Indexed on 2010/04/04 2:43 UTC
Read the original article Hit count: 411

Me and two other colleagues are trying to understand how to best design a program. For example, I have an interface ISoda and multiple classes that implement that interface like Coke, Pepsi, DrPepper, etc....

My colleague is saying that it's best to put these items into a database like a key/value pair. For example:

Key       |  Name
--------------------------------------
Coke      |  my.namespace.Coke, MyAssembly
Pepsi     |  my.namespace.Pepsi, MyAssembly
DrPepper  |  my.namespace.DrPepper, MyAssembly

... then have XML configuration files that map the input to the correct key, query the database for the key, then create the object.

I don't have any specific reasons, but I just feel that this is a bad design, but I don't know what to say or how to correctly argue against it.

My second colleague is suggesting that we micro-manage each of these classes. So basically the input would go through a switch statement, something similiar to this:

ISoda soda;

switch (input)
{
   case "Coke":
      soda = new Coke();
      break;       
   case "Pepsi":
      soda = new Pepsi();
      break;
   case "DrPepper":
      soda = new DrPepper();
      break;
}

This seems a little better to me, but I still think there is a better way to do it. I've been reading up on IoC containers the last few days and it seems like a good solution. However, I'm still very new to dependency injection and IoC containers, so I don't know how to correctly argue for it. Or maybe I'm the wrong one and there's a better way to do it? If so, can someone suggest a better method?

What kind of arguments can I bring to the table to convince my colleagues to try another method? What are the pros/cons? Why should we do it one way?

Unfortunately, my colleagues are very resistant to change so I'm trying to figure out how I can convince them.

© Stack Overflow or respective owner

Related posts about dependency-injection

Related posts about inversion-of-control