DEV Community

Tin Trinh
Tin Trinh

Posted on

Effective Java Part 5 - Prefer dependency injection to hardwiring resource

There are a ton of situations that you need to create an object that depends on the other objects. In those situations, using Singleton or static class is not appropriate.

It's better to have the class constructor to allow to pass in the resource that needs to parameterized the constructed object instead of using setter to change its behavior that may cause the class hard to test and maintain as well as hard to track its status transformation.

When writing the constructor, let's think about what we really depend on when we create the object. And pass those dependencies in the object is somewhat called dependency injection.

Nowadays, there are lots of framework help to do dependency injection easily so we don't have to do it manually. But the idea of them is the same. By showing the interface of what we depend on in the constructor and satisfy those dependencies when initiating them.

Top comments (0)