Junior — Middle
Can you explain what the idea of dependency injection in software design is?
sobes.tech AI
Answer from AI
The idea of Dependency Injection (DI) is to separate the creation and management of object dependencies from their usage. Instead of the class creating or finding its dependencies itself, they are passed to it from outside.
This increases modularity, makes testing easier (mock objects can be substituted), and simplifies code maintenance.
Example: instead of creating a service object inside the class,
class UserService {
private UserRepository repo = new UserRepository(); // hard dependency
}
we pass the dependency through the constructor:
class UserService {
private UserRepository repo;
public UserService(UserRepository repo) {
this.repo = repo;
}
}
Now, UserService is not responsible for creating UserRepository, but receives it from outside, which makes it easy to change the implementation and test the class.