Thursday, June 17, 2010

Constructor Vs. Setter Injection

Are we supposed to use setters (or properties) or constructors with dependency injection. There has been all kinds of opinions about the matter.

For me the decision is rather simple. Dependency injection should be noninvasive; after all, that is one of the reasons why we utilize it so much. A framework like Spring should not really change your class design one way or the other. Imagine that dependency injection does not exist - then how would you design your classes?

When constructing an object, you should use the constructor for all those dependencies that are required for the object to function. Setters/properties would then be reserved for changing default behavior. There should not be a requirement to call all these setters to make object functional. That is the job of the constructor.

True, setter injection can be convenient because you are dealing with named properties. In .NET (with Spring.Net), you can also name the constructor parameters so this is really a non-issue there. Setter injection can also be nice when there are so many parameters in the constructor that things become unwieldy. However, there are always ways around this limitation by providing proper abstractions for the constructor arguments.

In any case, the strongest argument that I have has to do with OOD and the promise of transparency of the injector framework for the rest of your program. Do not design your classes in such a manner that is somehow dictated by the dependency injection framework.