I just stumbled across an article byÂ Steve Schols in which he compares dependency injection via setter with constructor injection. And he prefers setter injection.
I don't agree. I especially do not agree with his arguments. Lets take them one by one.
What are the problems with constructor injection?
No reconfiguration and re-injection
Why would you want to do that? One reason why many programs are so difficult to think about is that stuff changes around. Think about it. If the state of an object is defined by its constructor you just have to find the place where your object got created in order to understand how it looks like at run time. If the state can be changed through setters you have to find every place where the setter gets called AND if the program control actually came across these places AND in which order in order to understand what state your object is in.
So don't change the state of your objects.
you could create a circular dependency using Spring. But not by using constructor-based injection
Excuse me? How is this possibly a drawback. I spent a lot of time to fix problems caused by circular dependencies. Using constructor injection prevents many circular dependencies. Absolutely a good thing.
He also quotes the spring reference documentation:
The Spring team generally advocates setter injection, because large numbers of constructor arguments can get unwieldy
Again constructor injection shows you you have a problem. I have yet to see a class that has more then three dependencies which adheres to the Single Responsibility Principle.
So if you run into problems with constructor injection congratulation! You just found a strong indication of a design problem in your application. Go ahead fix the design problem and proceed using constructor injection.
Of course there are situations where you can't fix the design problem and in these cases setter injection is a valid workaround. But it is just that: A workaround.
Wan't to meet me in person to tell me how stupid I am? You can find me at the following events:
- Spring Data JDBC - New Kid on the block.
- Softwaredevelopment in the 21st century.
- Domain Driven Design mit Relationalen Datenbanken und Spring Data JDBC.
- Kerbal Space Program, Glücksspiel und Psychologie und was das mit dem (Berufs)leben zu tun hat.
- Javaland Freeletics
- Domain Driven Design mit relationalen Datenbanken und Spring Data JDBC
- The New Kid on the Block: Spring Data JDBC