alexcuesta

My tech blog

Archive for July 2011

Constructor Injection vs Setter Injection

with 3 comments

My opinion is that we should initialize an object by passing all collaborators in the constructor. That’s the Java natural way to initialize an object correctly. Other mechanisms such as Spring annotations (@Required) are artificial ways to achieve the same goal.

Why?

  • Constructor-injection automatically enforces the order and completeness of the instantiated.In other words, it prevents the object to work with ‘null’ collaborators.
  • Enforces the order of initialization and prevents circular dependencies

Are you insane? My constructor has lots of arguments!

If you have many collaborators in the constructor, that means your class may have too many responsabilities. That’s not a good practice. Remember the Single Responsability Principle. More than three is too many! Your tests will get complicated because you’ll have lots of different combinations to setup each scenario.

That doesn’t mean that in some situations we need to use setters (Legacy code and no time for refactoring?). In this case, use the @Required annotation to ensure Spring initializes all dependencies.

Information about this:

Spring Blog:

http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/

Minsko Hevery, Agile Coach at Google:

http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/

Richard Paul about testing these objects:

http://www.rapaul.com/2011/07/10/constructor-injection-unit-tests/

Written by alexcuesta

July 28, 2011 at 12:59 pm

Posted in Java