Sobes.tech
Intern

Why is Dependency Injection needed?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a pattern that allows dependencies of an object to be passed from outside, rather than created inside. This is necessary for:

  • Simplifying testing (easily replacing dependencies with mocks).
  • Increasing flexibility and extendability of the code.
  • Improving readability and maintainability of the code.

Example in Java using a constructor:

class Service {
    private final Repository repo;

    public Service(Repository repo) {
        this.repo = repo; // dependency is passed from outside
    }

    public void doWork() {
        repo.save();
    }
}

Here, Service does not create Repository itself but receives it from outside, which makes it easier to replace the implementation during tests or changes.