Sobes.tech
Middle

What is Inversion of Control?

sobes.tech AI

Answer from AI

This is a design principle where the flow of program execution is controlled by a framework or third-party library, rather than directly by the application code.

Main ideas:

  • Inversion of Control: Instead of objects creating or looking up their dependencies themselves, this responsibility is delegated to an external container.
  • Dependency Injection: The container "injects" the necessary dependencies into objects, usually through constructors, setters, or interfaces.
  • Flexibility and Testability: It simplifies testing, as dependencies can be easily replaced with mock objects. It increases the flexibility and modularity of the application.

Example using the Spring framework:

// Dependency interface
interface HelloService {
    String greet(String name);
}

// Concrete implementation of the dependency
class HelloServiceImpl implements HelloService {
    @Override
    public String greet(String name) {
        return "Hello, " + name;
    }
}

// Class using the dependency
class GreetingController {
    private final HelloService helloService;

    // Dependency injection via constructor
    public GreetingController(HelloService helloService) {
        this.helloService = helloService;
    }

    public String sayHello(String name) {
        return helloService.greet(name);
    }
}

In this example, GreetingController does not create an instance of HelloServiceImpl. Instead, the Spring container (or another IoC container) creates both objects and passes the HelloServiceImpl instance to the GreetingController constructor.