In the post Inversion of Control (IoC), I described what was. Here I describe several examples of Inversion of Control.
Dependency Injection
When creating a class or module, it is good practice to reduce concrete dependencies when possible (Dependency Inversion Principle) . Concrete means having a hard dependency on another piece of code rather than a dependency on an abstraction.
This can be illustrated by defining a class. For example, a BillingForm may depend on a PaymentProcessor:
class BillingForm {
constructor() {
this.processor = new PaymentProcessor();
}
processForm(...) {
this.processor.process(...);
}
}
Contrast above with the following example where the dependency is added as an argument when constructing a BillingForm instance.
class BillingForm {
constructor(paymentProcessor) {
this.processor = paymentProcessor;
}
processForm(...) {
this.processor.process(...);
}
}
const paymentProcessor = new PaymentProcessor();
const billingForm = new BillingForm(paymentProcessor);
This is an example of IoC because the control of when a dependency is added is controlled by when the BillingForm is instantiated rather than immediately during the BillingForm instantiation.
React Lifecycle Methods
The Javascript frontend framework React.js has component lifecycle methods for components. Examples like componentWillMount
, componentDidMount
, and componentWillUnmount
are defined in a component. These methods can be overridden by a component. The methods are then called at the appropriate time by the React.js framework.
Other examples includes: Command Line Interface, Javascript callbacks, Route Handlers, Object oriented class frameworks, and User Interfaces