Understanding: Inversion Of Control (IoC)

Armando Ávila Bueno
3 min readFeb 6, 2021

Inversion of control is a design principle used in Object Oriented Programming (OOP), it allows a framework to regain some control from the application.

As said by Martin Fowler in this article, Inversion Of Control kind of started to be talked as an User Interface (UI) subject. Back in the day, user interfaces were controlled by the application, let’s say you wanted to use a “Rectangle Area Calculator”, something like this:

Figure 1

You can observe in “Figure 1” how the code of the application is in control, because it dictates when to prompt the user and when to pick up a response. Later, graphical UI frameworks came along and allowed us to develop software like this one:

Figure 2

Now, the UI framework through event handlers (button clicked) decides when to call the application code, the UI framework is now in control. It is basically applying the Hollywood’s Law:

Don’t call us, we’ll call you

The framework is telling the application “don’t call me, I’ll call your code when I need it”. By doing this, we’re now inverting the control from the application to the framework and therefore making the application a lot more flexible.

Well, that was how IoC was brought to the table years ago, nowadays we have another interpretation, pretty similar yet simpler:

Objects shouldn’t create the objects on which they depend, they should get them from outside.

If you want you can add “methods” to the previous statement, but anyway, let’s see a code example of what begginer programmers tend to do when they’re starting:

Example 1

In the example above is fair to say that the Ferrari and the Lamborghini classes are tightly coupled to the Motor class, because they depend on it and they also need to know how to create a Motor object, this situation makes the application not to be flexible, what happens if you change the constructor of the Motor class?

Example 2

Your application will crash because Ferrari and Lamborghini classes don’t know how to construct a Motor object anymore, besides, they’re breaking the Hollywood’s Law, they’re calling instead of waiting to be called. In this example Ferrari and Lamborghini classes have control, let’s invert that:

Example 3

That’s it, it’s now inverted, why? Ferrari and Lamborghini still need a Motor, but they don’t create it themselves, they don’t know how to create one, instead they get it from outside. They don’t care about how to create a Motor, they don’t know who creates the Motor and they’re not calling, they gave up control to whoever wants to call them.

With little changes like this one you can make your code easy to plug into your application making it more scalable and less prone to crash due to code changes.

--

--