Over a million developers have joined DZone.
Platinum Partner

Stuck-in-The-Matrix arguing between constructor and setter injection...

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

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.


 From http://tech.finn.no/Dependency-Injection-with-constructors/

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.

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}