Nicolas Frankel is an IT consultant with 10 years experience in Java / JEE environments. He likes his job so much he writes technical articles on his blog and reviews technical books in his spare time. He also tries to find other geeks like him in universities, as a part-time lecturer. Nicolas is a DZone MVB and is not an employee of DZone and has posted 217 posts at DZone. You can read more from them at their website. View Full User Profile

Dependency Injection on GUI components

04.09.2012
| 4024 views |
  • submit to reddit

For some, it goes without saying but a recent communication made me wonder about the dangers of implicitness in it.

In my book Learning Vaadin, I showed how to integrate the Vaadin web framework with the Spring DI framework: in order to make my point, I wired Vaadin UI components together. I did this because I didn’t want to go into the intricacies of creating a service layer. I had some comments questioning whether injecting UI components was relevant. The question applies equally to Vaadin and Swing. IMHO, I think not and if there’s a second version of Learning Vaadin, I will either write a warning in big bold font or choose a more complex example.

Why so? Here’s my reasoning so far. There are some reasons to use DI. To just name a few:

  • If I wanted to be controversial, I’d say that some use it because it’s hype (or because they’ve always done so)… but people that know me also know I’m not this kind of guy.
  • Some developers (or Heaven forbids, architects) use DI because it breaks dependencies
  • As for myself, the main reason I use DI is to make my classes more testable.

Now, UI components may have to collaborate with 3 other kinds of components: other UI components, GUI behavior and services. Since I consider the Vaadin framework to be top quality, I won’t unit test available components, only the behavior I’ve coded (more info on how to separate UI components and their behavior here) and services. Therefore, wiring  UI components together has no real value for me.

Injecting behavior and services is another matter: since those will likely need to be unit-tested and have dependencies themselves (either on the service layer or the data access layer), I need them to be provided by the DI context so they’ll be injectable themselves. At this point, there are basically two solutions:

  • Either wire only services and behaviors. This will lead to a dependency to the DI framework in the UI components.
  • Or wire all components at the root and let the framework handle injection. This may be overkill in some cases. This is the choice I made when writing the example for Learning Vaadin.

I hope this post will clarify the whole inject UI components thing for you dear readers.

Published at DZone with permission of Nicolas Frankel, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)