Sobes.tech
Junior — Middle

Explain the principle of inversion of control and why it is used in programming.

sobes.tech AI

Answer from AI

Inversion of Control (IoC) is a design principle where the control of creating and binding objects is delegated to an external container or framework, rather than being implemented directly in the code.

Why is this needed:

  • Loosening coupling between components — objects do not create dependencies themselves but receive them from outside.
  • Simplifying testing — dependencies can be easily replaced with mocks.
  • Increasing flexibility and extensibility — configuration changes, not code.

In Java, IoC is often implemented through Dependency Injection, for example, using the Spring Framework. Instead of creating objects directly, you describe dependencies, and the container injects them.

Example:

public class Service {
    private final Repository repository;

    // Dependency is injected via constructor
    public Service(Repository repository) {
        this.repository = repository;
    }

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

Here, the Service class does not create the Repository itself but receives it from outside, which facilitates replacing the implementation and testing.