views:

176

answers:

5

I'm trying to wrap my head around Dependency Injection.

One of the things I'm confused about is whether all of your object instantiation needs to be controlled by the DI framework (Spring, Guice, etc).

Or, if not, how do you determine which objects are instantiated by the framework and which objects are instantiated with the new operator?

+7  A: 

No, there's still a place for new. Not all objects need be under the DI factory's control.

You can easily spot the classes that need to be under the DI factory's control, because they usually involve interfaces and implementations.

Any local object in an implementation is entitled to call new. Model objects instantiated to satisfy a particular use case should be instantiated by calling new and passing the parameter values for that particular instance.

duffymo
+1  A: 

As long as newing-up doesn't prevent you from isolating units of behaviour for testing, you're alright. Examples might be creating collections or value types used within an implementation, but not actually doing "object work," per se.

Focus on the word "dependency" -- is the object in question relied upon in some way for the containing object to fulfill its one true purpose for existing? If so, it should be injected from without.

Jay
+8  A: 

I've found this post by Miško Hevery very helpful in distinguishing between which objects should be injected as dependencies and which it's OK to create. He distinguishes between 'Newable' and 'Injectable' classes.

Ben Lings
A subtext of Miško's article is that doing Test Driven Development often makes it obvious when to use DI.
toolbear74
A: 

new doesn't necessarily rule out DI frameworks. In Spring, for example, you can use classloading magic to perform dependency injection on any object created by new.

So while new and container-driven DI in java are usually mutually exclusive, this isn't a hard and fast rule.

skaffman
+1  A: 

I'd say simpler Objects with no 'real' dependencies should not be injected. These could be data objects or, of course, exceptions and the like.

The 'eliminats the new operator' thing basically just gives a good guideline where to look for DI-able stuff.

Hans Wagner