What is IoC?

Share

Inversion of control (IoC) is a programming principle in software engineering. IoC inverts the traditional control flow. With the IoC methodology, custom-written portions of a computer program receive the flow of control from a generic framework.

In traditional programming, the custom code, which expresses the purpose of the program, calls reusable libraries to take care of generic tasks. Unlike IoC, it is the framework that calls these reusable libraries into the custom, or task-specific, code.

svg viewer

Although reusable code and problem-specific code operate together in an application, the inversion of control strongly connotes that they are developed independently.


Process

svg viewer

Examples

Code

See the code below of a simple response method. This method is displayed by most patterns such as .NET and Enterprise Java:

public class ServerFacade {
public <K, V> V respondToRequest(K request) {
if (businessLayer.validateRequest(request)) {
Data data = DAO.getData(request);
return Aspect.convertData(data);
}
return null;
}
}

It is important to note that a lot of assumptions are made about the data returned by the data access object (DAO) in the ServerFacade class.

Although all these assumptions may be valid at some point, they couple the implementation of the ServerFacade to the DAO implementation.

Code

The following ​response outline in Java gives an example of code following the IoC methodology:

public class ServerFacade {
public <K, V> V respondToRequest(K request, DAO dao) {
return dao.getData(request);
}
}

Designing the application in the manner of inversion of control would hand over the control completely to the DAO object as shown above.

Copyright ©2024 Educative, Inc. All rights reserved