/ UNIT TESTING, USER INTERFACE

Dependency Injection on GUI components

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.

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Dependency Injection on GUI components
Share this