June 17, 2010

Constructor Versus Setter Based Dependency Injection

There seems to be two extreme camps here and no middle ground.

I, as usual, agree with neither extreme.

The simple fact is that my preferred approach is to design classes that meet the original intent of object orientation. That the class is fully usable after construction.

That is not to say that I believe that Constructor injection is the one, true way. Rather, I believe that all mandatory dependencies should be configured in the constructor and optional ones should be satisfied by setter methods. This makes the class much easier to understand. It also means that the constructor does not end up completely overloaded with parameters but neither are you left looking at a a sea of setter methods wondering which ones have to be used.

By using this convention the code becomes more self-documenting.

No comments: