Junior — Middle
What method of dependency injection is considered most recommended in modern programming practices?
sobes.tech AI
Answer from AI
The most recommended method of dependency injection in modern practices is constructor injection.
Advantages:
- Ensures immutability of dependencies after object creation.
- Allows easy testing of the class by substituting mocks or stubs.
- Clearly shows what the class depends on.
Example in Java:
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public void doWork() {
repository.save();
}
}
Here, Repository is passed through the constructor, which simplifies dependency management.