DEV Community

Cover image for IoC: Inversion of Control principle

IoC: Inversion of Control principle

le0nidas profile image le0nidas Originally published at on ・2 min read

This is the one principle that, chances are, you have applied even if you didn’t do it on purpose.

In essence, if you have written code that does not have any control over the execution flow, then you most probably have applied the IoC principle. How?

IoC through design patterns

If you have implemented the strategy or the template pattern then you have applied the IoC principle. For example, having a report generator and feeding it with the necessary filtering code.

All the code you write for filtering data, does not have any control over the execution’s flow. The generator is the one that decides when and if it will be invoked:

Strategy pattern

The same goes with the template pattern too. The code you write in the template’s hooks is being controlled by the template and you don’t get to control it:

Template pattern

Both of these examples might seem weird since we are the ones that wrote both the filtering code and the generator so we feel that we control the flow. The thing is that we need to separate them in our heads and observe them individually. The generator is the one that controls the flow and dictates the actions that will take place. The filtering code is one of the actions. We just write them, provide them to the generator and that’s it.

IoC through frameworks

Another way of applying IoC is by using frameworks that have adopted it. Most popular are the IoC containers that are used to inject dependencies.

Another example is the android’s framework. In android you don’t have control over an activity’s lifecycle and you simply extend the Activity class and override hooks to run your code.

IoC vs DI

Because of the aforementioned IoC containers, many people assume that dependency injection and IoC are the same. They are not. DI is just a way to help in applying the IoC principle. For example:

we can change the generator and have the filtering code being injected to it by constructor. The inversion is already happening, DI is simply used to provide the extra code.

Discussion (0)

Forem Open with the Forem app