Monday, November 19, 2012

Effective dependency injection

In the introduction the presenters stated that this was a talk about how to use depency injection in general in an effective way, not targeted at a specific product. Both presenters work for google, so they chose Guice for their code examples. The majority of the talk turned out to be tips and suggestions on how to effectively use Guice. They used a number of specific api classes and mostly appended "I'm sure the other frameworks provide something similar". I've tried to translate some of their tips into a more general form.
  • Prefer explicit binding over autowiring and letting the framework decide on which implementation to inject. Especially if you write modules that can be reused.
  • Favor constructor injection over property injection: this way you get immutable classes and get the benefit of thread safety for free. The other benefit is that all your members will be initialised correctly and your object is created in a stable state.
  • Avoid doing work in constructors, keep them as simple as possible and do initialisation in a separate init method that can throw exceptions if necessary.
  • Write system tests that verify that all your dependencies are wired correctly.
  • Avoid deep inheritance graphs. Always favor composition over inheritance (which is a principle of OO programming in general).
The speaker in this talk contradicted Kirk Knoernsschild on how to modularity. He would advise to put the interfaces, the implementation and the consumer in the same package, so that you don't need to expose public implementation classes. However when you would use OSGi, you would have to compromise that because exported classes should be public there. I his oppinion there is hardly any need for things like Jiggsaw or OSGi. The only reason to use it would be when you have an architecture based on plugins like eclipse that needs runtime extensibility or when you have different modules that require different versions of the same module.


A lot of people had great expectations from this session on dependency injection. All seats were taken, all stairs were full, people even sat on the ground in the front. My curiousity kept me in the room for an hour, but the talk wasn't worth the sore back in the end.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.