views:

677

answers:

5

I'm relatively unskilled in Dependency Injection, and I'd like to learn some best practices and anti-patterns to use and avoid respectively when using DI.

A: 

I've found that when I see a violation of the Law of Demeter that is a hint that I might want dependency injection.

For example:

void doit()
{
    i += object.anotherobject.addvalue; //violation of Law of Demeter
}

Sometimes hints that I might want to dependency inject anotherobject.

Alex B
Seems a little arbitrary...
Robert Harvey
A: 

My basic rule about when to use DI is that I will inject between layers, so between my controller and the dao would be a layer, so I can inject, so that if I want to mock out a layer I can.

I think using DI within the same layer is not a good idea mainly because the layer should be tightly coupled, as they are related, unless you have a user story that makes it useful.

For example, if your DAO is may be on separate computers then you may need to be able to pretend that they are one layer, but use DI to actually switch between all on one machine and separate machines. Then the developer can do everything on one machine and it should work on separate machines.

But, unless there is some pressing need, I think DI within the same layer is an unnecessary complication.

James Black
Well using dependency injection within a layer you will re-use existing component instances, conserving resources. Also I would say you are fostering good programming habits by forcing a modular design.
Christoffer Soop
I just see it getting more complicated than it needs to be, but that depends on what is on the layer. I tend to just do it between layers, but that is why I explained why doing it between a layer can be helpful, just not something I will suggest.
James Black
+1  A: 

In my opinion, Dhanji Prasanna's book Dependency Injection is a must read for software designers, both beginners and experts. It deals directly with your DI questions.

jnorris
+3  A: 

I really enjoyed this article regarding DI, as it's targeted towards people who don't have a ton of DI experience, or don't even know what it is.

http://mtaulty.com/CommunityServer/blogs/mike%5Ftaultys%5Fblog/archive/2009/08/10/rough-notes-on-unity.aspx

What’s Unity?

It’s a “dependency injection container”.

Now, at that point a bunch of folks reading this will say “Yes, we know and we’re already using it for reasons A, B, C or we’ve elected not to use it for reasons X,Y,Z ” and I imagine a bunch of other folks might say;

“Huh? What’s a dependency injection container?”

This post is for the latter people – it’s not meant to be exhaustive but hopefully it’s not completely unhelpful either :-)

Samuel Meacham
+2  A: 

There's a best practices section in Guice's user's guide.

Jesse Wilson