Wednesday 21 October 2009

Guice in a Java Swing App

Recently I have been working on a project that as normal uses Swing but decided to use Guice to avoid some of the problems that I’ve encountered in previous projects.

The problem is that if you have components that rely on service type interfaces that are nested several layers deep (not that unlikely in a complex UI) then to pass the service to the component all the other components above it need to have methods/constructors that pass the service down the hierarchy. This culminates in a simple change to a component that needs a reference to a new service requiring changes to 4/5 classes that also now have references to something they didn’t need to know about. This means extra coupling and more pain when you’re trying to refactor.

So now there are panels which have references to components that are themselves injected, which have injected services and everything works. It just works. In fact I barely think about it anymore, components with dependencies are just injected and there are no problems, no extra dependencies and no extra work. If the injected components also need service dependant components then they are injected as well and have no impact up the hierarchy.

Many classes in the project now have no code depending on the way they are created, which is a real joy. I haven’t heard this benefit touted by IoC propaganda but it really should be. If you ever wondered if adding dependency injection was overkill for you project, note down what you would inject. If there is more than two (my own measurement) injectable classes then the gains will be more than the cost of complexity in setting up the IoC infrastructure with modules and injectors etc.