If you have passed your courses about object oriented programming, you know that loose coupling is something you should always strive for. There are many ways to achieve loose coupling. Inversion of control (IoC) using dependency injection (DI) is one way to improve the quality of your code.
When a developer asks me how they should build a “full-stack application”, I pretty much always suggest basing their application either on Java EE or Spring. One of the reasons is the DI containers that both technology stacks provide. Many developers and architects are a bit afraid of this “magic” that inversion of control and dependency injection bring in, often for the wrong reasons.
Last week we had a webinar with my colleague Petter Holmström about dependency injection. If you want to get an idea of what dependency injection is or just want to refresh your knowledge of the subject, you should definitely check it out. In the webinar we discuss if, why and when you should use dependency injection in your applications and go through the basic principles and alternatives.
The key takeaways of our webinar:
-
Loose coupling and high cohesion (and all the advantages they bring) are the main things we aim for with DI.
-
When starting with DI, learn the basic concepts well and watch out for the pitfalls. Otherwise the DI container will cause you more harm than good.
-
Contexts and events will further help you create reusable and maintainable code.
-
There is no need to bring in “all the magic” of the Spring or Java EE technology stacks. I like to use DI even in the simplest cases because Vaadin CDI and Vaadin Spring make it easier to use Vaadin compared to the plain servlet approach and setting everything up yourself.
-
There are multiple DI containers to choose from. Vaadin has integrations for three of them:
-
There are also alternative mechanisms that you can use if you for some reason aren’t able to use a DI container. Simply by designing your code using IoC patterns, you can achieve loose coupling and high cohesion.
Our Java EE training also discusses DI and how to use it in your Vaadin applications. If you want more hands on training about dependency injection, join our next course!