Skip to content
Rex St. John

Get in touch

What is Inversion of Control?

When I first encountered the concepts of inversion of control and dependency injection, I found the available explanations on the internet to be written in impenetrable “nerd speak.”

Originally published on the rexstjohn.com blog

What is Inversion of Control?

Originally published at rexstjohn.com on November 10, 2013. Recovered from the Internet Archive.

A Non-Inverted Control Scheme

Your control lacks inversion

When I first encountered the concepts of inversion of control and dependency injection, I found the available explanations on the internet to be written in impenetrable “nerd speak.”

This is the dependency injection and inversion control explanation I wish I could have read at that time.

A Simple Analogy

Let’s begin by comparing the operations of two restaurants: HamburgerTown and Mel’s Diner.

At HamburgerTown, hungry customers stand in line at the counter, order, pick up their food and then sit down to eat. The customer in this situation needs to know a number or things…where the counter is, where the kitchen is, where to get food and where to sit afterwards.

The customer is entirely in charge of knowing, identifying and fulfilling their own needs.

The Injection Process In Action

The Injection Process In Action

At Mel’s Diner, customers enter the restaurant, sit down and are given menus. When the customer is ready for food, they signal  their desires to the waitress, who scans their orders and then fetches their order from the kitchen automatically.

The customer is only in charge of  communicating their needs. An external entity does the leg work of detecting and resolving those needs automatically.

An Example Mobile Application

Let’s use the example of a Yelp-like application which gets a list of nearby restaurants.

In the “HamburgerTown” version of this application, the logic for fetching and populating the list of restaurants is owned entirely by the list’s view controller.

Some pseudo-code of a simple “View Controller” construct.

Class RestaurantListViewController: TableViewController{

     // Array of restaurants to be fetched from our remote service
     private Array restaurants;
     // Service for fetching restaurants
     private Service restaurantsService;

     // Psuedo-code initialization
     public void init(){
        self.restaurants = new Array();
	self.restaurantsService = new restaurantsService();

	// Fetch the restaurants.
	self.restaurantsService.fetchRestaurants(onRestaurantsFetched);
     }

     // Method for handling restaurants fetched events
     private void onRestaurantsFetched(Array fetchedResults){
	self.restaurants = fetchedResults;
        self.tableView.dataSource = restaurants;
        self.tableView.reloadData();
     }
}

In this situation, the view controller is in charge of identifying and fulfilling it’s own data needs.

Notice that no external opportunities are provided here to influence how this table view controller fetches data. The view controller depends on some service internally in order to do it’s own job. Lets talk about why this is potentially an anti-pattern.

HamburgerTown: It Isn’t Testable

Automated testing is widely recognized as a good way to help ensure that large complex systems continue to perform reliably and don’t break down unexpectedly due to subtle bugs introduced during regular coding work.

A key requirement of automated testing is that it should be possible to remove individual software components from the overall system and verify their behavior.

The problem with having each view controller entirely in charge of it’s own data fetching is that all of this logic is now hidden inside that view controller.

We have also introduced an internal dependency which makes it difficult to extract our view controller from the system: The view controller depends on some service object internally in order to do it’s own job properly.

This problem may be solved by introducing a “dependency injector” and “inverting control” over where the data fetching logic sits. We must completely remove the dependency the view controller has on any external service.

Note: Another solution might be to introduce something called a “Service Locator.” The service locator pattern works by having some mechanism of “injecting” a service (or otherwise dynamically resolving this dependency) into your class dynamically. Many believe the service locator pattern to be an “anti-pattern” because the view controller still depends on another object (the service) in order to do it’s own job.

The Injector Intelligently Identifies and Fills Dependencies

Mel’s Diner represents the “Inversion of Control” pattern: The view controller is solely responsible for exposing it’s own needs and some external entity will read these and then inject them automatically.

Here is an example in pseudo-code of what an inverted view controller would look like.

Class RestaurantListViewController: TableViewController{

     // Array of restaurants fetched from our remote service
     private Array restaurants;

     // Psuedo-code initialization
     public void init(){
        self.restaurants = new Array();
     }

     // All we do here is expose what dependency we require filled.
     public Array getDependencies(){
	return (Array:"restaurants");
     }

     // React when the restaurants dependency is injected.
     public void setRestaurants(Array _restaurants){
        self.tableView.dataSource = restaurants;
        self.tableView.reloadData();
     } 
} 

// Time to load the restaurants list! 
RestaurantListViewController restaurantsController = new restaurantListViewController(); 
Injector injector = new Injector(); 
injector.inject(restaurantsController);

The above example is purposefully very sparse and ultra-basic, but the core tenets are there: The injector scans the view controller (often using a technique known as reflection) for it’s dependencies and automatically resolves them. Control is said to be “inverted” because it is now someone else’s job to resolve dependencies.

Some Mobile IOC Frameworks

RoboGuice for Android
Dagger for Android
Objection for iOS