Sobes.tech
Junior — Middle

Explain the principle of inversion of control using the example of a taxi calling system.

sobes.tech AI

Answer from AI

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

Example in a taxi call system:

  • Instead of the TaxiService class creating Driver or Car objects itself, these dependencies are passed to it from outside (for example, through the constructor).
  • The IoC container is responsible for creating and binding all objects.
public class TaxiService {
    private Driver driver;

    // Dependency is passed from outside
    public TaxiService(Driver driver) {
        this.driver = driver;
    }

    public void callTaxi() {
        driver.driveToCustomer();
    }
}

Here, TaxiService does not create a Driver itself but receives it from outside. This simplifies testing, extension, and maintenance of the code, as dependencies can be changed without modifying the class itself.

Explain the principle of inversion of control using… - sobes.tech