Inversion of Control

Inversion of Control (IOC): Concept

Inversion of Control a design pattern that most programmers don’t know about, even if they probably have used (or been using) an implementation of it.

In order to understand this “Inversion of Control“, we must first have an understanding of what “control” means in this context.

Typical Control

What most of us programmers know of, and have been doing since we learned how to program is writing a sequence of commands in order for something to happen (that is, make our application accomplish something).

We (as the programmer of our application) control the flow or sequence of events within our application. This is especially true back in the console days when we write codes in (GW)BASIC, Pascal, even batch files.

This is approximately how a typical application was written back then, and even most applications written today:

Take note that your application decides what (function) to call and when to call it. The function (and/or statement) could either be a built-in function of the programming language (like PRINT) or those provided by a library (like ADD_NUMBERS).

Inverted Control

Considering the above definition of a “typical” control, then inversion of control means the reverse, right?

But, wait, does it mean I lose control of my application?

In terms of deciding the sequence of calls or events, then yes — you lose that part of control. But what you want to do when events happen, you still have control over them — you can still decide what to do.

This is how it would look like for an application that implements IOC:

Now, notice in this scenario that it’s the framework that decides which function/method to call and when. Our application only provides the detailed implementation for such methods/events.

Even the method signature and its return type is dictated/defined by the framework.

Don’t call us, we’ll call you

You can think of IOC design pattern as a potential employer — they tell you what you need to do and when to do them, what to bring and what they expect from you in return, etc. 🙂

Have you used a framework?

If you’ve been using #Python for a good amount of time, you’ve probably heard of #Django — a web framework written in #Python that allows you to quickly build a web application and easily extend it too.

In terms of IOC, you don’t really call Django to make something happen. For example, if you want to display your About page, you don’t tell Django to do it. Instead, you (or an end-user) uses a web browser and clicks/goes to the URL for your About page and then Django calls your code.

There are many other frameworks out there, and you can create your own framework too (if you want to).

I would write a follow up blog on IOC next time and show you how you can write one yourself. 🙂

Leave a Comment