Inversion of control is a software design principle that asserts a program can benefit in terms of pluggability, testability, usability and loose coupling if the management of an application's flow is transferred to a different part of the application.
IoC is often talked about as the Hollywood Principle, as in: "Don't call us, we'll call you." An IoC framework takes the management of an application's implementation away from the developer. When interactions occur that require custom business logic, an IoC framework will invoke code provided by the developer. This is the "inversion" aspect of the inversion of control design principle.
The most common application of IoC is in modern application frameworks such as Spring Boot, JAX-RS, Ruby on Rails, Hibernate and JavaServer Faces.
IoC frameworks implement common, low-level and problem-prone activities. This allows the developer to focus on custom business logic, instead of struggling with tedious infrastructure or configuration tasks.
Criticisms of IoC
A common complaint of the IoC design pattern results from the confusion over what qualifies as IoC and what does not.
The IoC design principle, for example, does not specify a problem domain within which it is meant to operate. It is not precisely clear what is meant by "control," and IoC does not specify where an application's control is best inverted to.
Further, IoC makes no guarantees about the benefits its implementation will have. The IoC design principle simply asserts that benefits may accrue if you invert the flow of an application.
Examples of IoC
Each of these markedly different changes to a software program can be legitimately described as IoC:
- the use of event-based user interfaces instead of ones controlled by procedural code;
- the use of a shared component cache, such as the Spring ApplicationContext, that is responsible for the creation and initialization of objects; and
- the use of a comprehensive framework that abstracts away complicated implementation details.
The wide range of development changes that qualify as IoC contributes to the imprecision of the term.
IoC and dependency injection
To avoid the confusion over the term IoC, dependency injection (DI) was coined to describe the specific IoC use case in which a software container provides a configurable application context in which pluggable objects are created, initialized, cached and managed. Popular DI containers include:
- The Spring ApplicationContext
- The Pico IoC Container
- Guava Guice
- Jakarta EE's Context and Dependency Injection container
Dependency injection is a form of IoC, but the relationship is not transitory. Not all IoC containers perform DI.