This 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...
Is there a bigger picture? Are we just stuck in a matrix not seeing the truth...
What about API design?
What about the differences between IoC and DI?
What about the different types of application?
Question everything…by remaining focused on what is required from the code at hand we can be pragmatic in a world full of rules and recommendations. By knowing: when what can, and for how long, be dropped; we can incrementally evolve complex code towards a modular design in a sensible, sustainable, and practical way.