[Effective Java] [Item 5] Prefer dependency injection to hardwiring resources

Опубликовано: 26 Апрель 2026
на канале: Omkar Shetkar
1,039
12

https://github.com/Omkar-Shetkar/effe...

Creating and Destroying Objects

Item 5: Prefer dependency injection to hardwiring resources

Inappropriate approaches
Use of static utility classes
Use of singletons
Static utility classes and singletons are inappropriate for classes whose
behavior is parameterized by an underlying resource

Dependency Injection approaches
pass the resource into the constructor when creating a new instance
DI is equally applicable to constructors, static factories, and builders
pass a resource factory to the constructor

Advantages of DI approaches
greatly improves flexibility, reusability, and testability

Disdvantages of DI approaches
it can clutter up large projects, which typically contain thousands of
dependencies
solution is to use DI frameworkds such as Dagger, Guice, or Spring