Sunday, April 12, 2009

Constructor injection FTW

I prefer using constructor injection with DI for a few simple reasons.
  1. It's self-documenting code. It's explicitly telling clients or maintainers of the component how it's put together.
  2. It keeps my components honest. In most cases, excessive constructor arguments is a code smell.
I also don't like setter injection for a few simple reasons.
  1. It adds noise to component's API. I wouldn't want to see public properties hanging off a component that serves's me no use as a client.
  2. It feels like it breaks encapsulation. How the component does its work internally shouldn't be part of its public API.
  3. It obfuscates how the component is put together.

1 comment:

Elliott said...

Exactly... Said it the same way myself many times!

Using an IServiceLocator helps with the pain a lot too; although, I agree that the pain usually the symptom, not the disease.