alexcuesta

My tech blog

Constructor Injection vs Setter Injection

with one comment

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/

Advertisement

Written by alexcuesta

July 28, 2011 at 12:59 pm

Posted in Java

One Response

Subscribe to comments with RSS.

  1. Great stuff, I didn’t know about the Spring blog post on this subject, it’s generally Spring code that has screeds and screeds of setter or reflection based injection. Cheers for the pingback.

    Richard Paul

    July 28, 2011 at 6:02 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.