Express Your Dependencies

Recently I gave a presentation on Test Doubles at a client site and while fielding questions at the end, one person asked how they could use Mockito (which I used to demonstrate Test Doubles) when autowiring fields with Spring. The problem he had was he was autowiring the fields, which were private, and which had no setters to use for injection. Although he could use reflection and cheat, I stated what I believe to be philosophically correct; dependencies should be expressed in your implementation (I often don’t express them in interfaces unless they are an argument based dependency) and as such you should always provide an injection method for them (constructor or setter) to realize that dependency to those who might use the concrete implementation.

So, rather than doing this:

public class SomeServiceImpl {
	@Autowired
	private Dao dao;
}

I’d prefer to do this:

public class SomeServiceImpl {
	private Dao dao;

	@Autowired
	public void setDao(Dao dao){
		this.dao = dao;
	}
}

Although one can argue that the setter is only used for substitution in tests/examples and there’s no client code at all that will inject the dependency besides Spring, I’d argue that your tests/examples are clients themselves… I’d also argue it’s just plain good design to express the external dependencies that your class requires. :)

You can leave a response, or trackback from your own site.

Facebook comments:

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!