The article takes an indepth look at when to and when not to use constructor injection by broadening the context that usually limits the debate between constructor vs setter injection.
We had a consultant working with us reminding us to take a preference towards Constructor injection. Indeed we had a large code base using predominantly setter injection because in the past that is what the Spring community recommended.
The arguments for constructor injection goes like:
- Dependencies are declared public, providing clarity in the wiring of Dependency Inversion,
- Safe construction, what must be initialised must be called,
- Immutability, fields can be declared final, and
- Clear indication of complexity through numbers of constructor parameters.
And that Setter injection can be used when needed for cyclic dependencies, optional and re-assignable dependencies, to support multiple/complicated variations of construction, or to free up the constructor for polymorphism purposes.
Being a big fan of Inversion of Control but not overly of Dependency Injection frameworks something smelt wrong to me. Yet solely within the debate of constructor versus setter injection i don’t disagree that constructor injection has the advantage. Having been using Spring’s dependency injection through annotation a little recently and building a favouritism towards field injection I was happy to get the chance to ponder it over, to learn and to be taught new things. What was it i was missing? Is there a bigger picture?