Inversion of Meaning

Sun, 15 Dec 2013 15:03:01 +0000

This is a rant; if you don't like rants, well just don't read it.!

Computer science is full of fuzzy terms, and cases where multiple concepts are mapped to the same term (shall we have the argument of whether an operating system is just the thing running in privileged mode or also includes any of the libraries? and whether we should call that thing Linux or GNU/Linux?). Usually I can just deal with it, there generally isn't a right answer, or if there ever was it has been lost in the mists of time. And of course, language is a living thing, so I get that the meaning of words change over time. But, never have I seen a term's meaning been so completely eviscerated as what has happened to the previously useful and meaningful term Inversion of Control, which has become completely conflated with the term Dependency Injection.

Wikitionary provides a relatively servicable definition of the term:

Abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to the traditional architecture.

A trivial example would be reading some data from the console. The usual flow of control would be something like:

function read_input()
   input = /* some magic to get the input */
   return input

function menu()
       input = read_input()
       /* Do something with the input */

function main()

The normal flow of control is that the application passes control to the read_input() function, the function returns with some result and then the application does something with the input. Now we can invert this by doing something like:

function input_reader(handler)
        input = /* some magic to get the input */

function menu_handler(input)
     /* Do something with the input */

function main()

In this example rather than the application code calling the read_input() function, the input reading code calls the application. That right there is the inversion!

So breaking it down; the control is normally passed from an application to a library (via a function call). If we invert this, i.e.: put in the opposite order, then the library passes control to the application and we can observe an Inversion of Control.

Such a pattern is also called the Hollywood Principle: Don't call us; we'll call you. (Don't ever accuse computer scientists of lacking a sense of humour!).

Of course there is nothing mind-blowing about structuring code like this. Clark discussed structuring system using upcalls [PDF] almost 30 years ago.

So, inversion of control isn't really a big concept. Pretty simple, straightforward, and probably not deserving of an 18 character phrase, but it certainly means something, and that something is a useful concept to use when talking about system design, so needs some kind of label.

A real-word example can be found in the C standard library, where qsort calls in to the application to perform a comparison between elements. Another example is the Expat XML parser which calls back in to the application to handle the various XML elements. Glib's main loop is probably another good example. I think it is interesting to note that size or scope of an inversion of control can vary. In the case of qsort, the inversion is very localised, by comparison in the Glib example, basically the whole program exhibits inversion of control.

The one quibble I would have with the Wikitionary definition is using the use of the word principle. To me a principle implies some desirable design aspect that you generally strive towards. For example, the Principle of Least Privilege or the Separation of Concerns principle.

Inversion of Control is not really something you strive towards. In fact it can often lead to more complex designs. For example, when parsing XML it is generally simpler to call a function that converts the XML data into a document object model (DOM), and then make calls on the DOM, compared to an Expat or SAX style approach. Of course, there are advantages to the Expat/SAX approach such as reduced memory footprint. The point here is that Inversion of Control is a consequence of other design goals. No one starts out with the goal of: let's design this system so that it exhibits inversion of control (well, OK, maybe node.js did!). Rather it is a case of: so that we could achieve some specific design goal, we had to design this part of the system so that it had inversion of control.

If you didn't really like my description of Inversion of Control, I can recommend reading Martin Fowler's article, which I think does a pretty good job of explaining the concept.

However, the final paragraph of the article starts to point to the focus of this rant:

There is some confusion these days over the meaning of inversion of control due to the rise of IoC containers; some people confuse the general principle here with the specific styles of inversion of control (such as dependency injection) that these containers use. The name is somewhat confusing (and ironic) since IoC containers are generally regarded as a competitor to EJB, yet EJB uses inversion of control just as much (if not more).

This starts to introduce new terms such as IoC containers (see, I told you 18 characters was too much, look how swiftly it has been reduced to a mere 3 characters!) and dependency injection. When I first read this, I had no idea what Martin was talking about. What is an IoC container? What is dependency injection? (I'm ashamed to say I did know that EJB was an Enterprise JavaBean.) And my curiosity in to this final paragraph let me on a magical journey of discovery where the more I read the more I thought that I must have been confused about what IoC is (and I'm pretty sure if been using the term off and on for over 11 years now, so this was a bit of a concern for me!). So, if you are still reading you get to come along with me on a ride of pedantry and computer science history as I try to work out why everyone else is wrong, because I know I can't be wrong!

Let's start with Wikipedia. The first paragraph of the Inversion of Control article on Wikipedia defines IoC as:

a programming technique, expressed here in terms of object-oriented programming, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.

I'm really not sure what sort of mental gymnastics are required to get from my definition to a definition such as that. They are certainly beyond my capabilities. But it's not just Wikipedia.

The top answer on StackOverflow question What is Inversion of Control? isn't much better:

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

Sorry, I don't get it. Inversion of Control is all about, you know inverting control. At least this explicitly conflates IoC with this dependency injection thing, which gives us some hope of tracing through time why these things seems so intertwined.

And just in case you thought it was just Wikipedia and Stackoverflow, you can pick just about any blog post on the subject (excepting Martin's previously linked above, and I guess this one, but that is a bit self-referential), and you'll find similar description. Just to pick a random blog post on the subject:

Inversion of Control (IoC) is an approach in software development that favors removing sealed dependencies between classes in order to make code more simple and flexible. We push control of dependency creation outside of the class, while making this dependency explicit.

Again this recurring theme of dependencies. At least all these wrong definitions are more or less consistently wrong. Somewhere in the history of software development dependencies and inversion got all mixed up in the heads of developers. It is interesting to note that most of the examples and posts on the subject are very object-oriented (mostly Java).

To get to the bottom of this I guess I need to learn me some of this dependency injection terminology (and learn how to spell dependency without a spell-checker... hint, there is no a!). Given the quality of the IoC article, I'm skipping the Wikipedia article. The canonical source (by proclamation of the Google mediated hive-mind) is Martin Fowler's article. His article on IoC was pretty good (apart from a confusing last paragraph), so this looks like a great place to start.

In the Java community there's been a rush of lightweight containers that help to assemble components from different projects into a cohesive application. Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name of "Inversion of Control". In this article I dig into how this pattern works, under the more specific name of "Dependency Injection"

Aha! I knew it was Java's fault! OK, so, about 10 years ago (2003), the Java community discovered some new pattern, and were calling it Inversion of Control, and Martin's article is all about this pattern, but he calls it by a different name Dependency Injection (DI). Well, I guess that explains the conflation of the two terms at some level. But I really want to understand why the Java community used the term Inversion of Control in the first place, when, as far as I can tell, it had a relatively clear meaning pre-2003.

So, these lightweight containers are mentioned as originators of this pattern, so they look like a good place to start investigating. One of those mentioned in Martin's article is PicoContainer. Unfortunately that goes to a deadlink. Thankfully, through to the awesomeness that is the Wayback Machine we can have a look at the PicoContainer website circa 2003. That website mentioned that it honors the Inversion of control pattern (IoC) but doesn't really provide any detail on what it considers the IoC pattern to be. Thankfully, it has a history section that attempts to shed some light on the subject: Apache's Avalon project has been selling the IoC pattern for many years now.

OK, great, so as of ~2003 this Avalon project had already been talking about the IoC pattern for many years. The Apache Avalon project has (unfortunately?) closed, but there seems to still be references and docs in various places. On bit of the project's documentation is a guide to inversion of control.

It introduces IoC as: One of the key design principles behind Avalon is the principle of Inversion of Control. Inversion of Control is a concept promoted by one of the founders of the Avalon project, Stefano Mazzocchi.

It goes on to provide a very different description of IoC to my understanding:

Chain of Command This is probably the clearest parallel to Inversion of Control. The military provides each new recruit with the basic things he needs to operate at his rank, and issues commands that recruit must obey. The same principle applies in code. Each component is given the provisions it needs to operate by the instantiating entity (i.e. Commanding Officer in this analogy). The instantiating entity then acts on that component how it needs to act.

The concrete example provided is:

class MyComponent
    implements LogEnabled
    Logger logger;

    public enableLogging(Logger newLogger)
        this.logger = newLogger;

    {"Hello World!");

With an explanation:

The parent of MyComponent instantiates MyComponent, sets the Logger, and calls myMethod. The component is not autonomous, and is given a logger that has been configured by the parent. The MyComponent class has no state apart from the parent, and has no way of obtaining a reference to the logger implementation without the parent giving it the implementation it needs.

OK, I guess with such a description I can start to see how this could end up being called inversion of control. The normal order of things is that a class creates its dependents in its constructor, however this pattern changes this so that the caller provides the dependents. This doesn't really feel like inversion to me, but I guess it could be considered this. And equally I don't really think there is control as such involved here, maybe control of dependencies?

I think you could claim that myMethod in the example exhibits some localised inversion of control when it calls the logger, but that isn't really what is identified by the any of the explanatory text.

Anyway, this isn't really a particularly pleasing place to stop; there must be more to this story.

Some extensive research work (OK, I just used google), led me to the aforementioned Stefano Mazzocchi's blog. On which he has an insightful post about the origins of the use of the term IoC within the Avalon community.

I introduced the concept of IoC in the Avalon community in 1998 and this later influenced all the other IoC-oriented containers. Some believed that I was the one to come up with the concept but this is not true, the first reference I ever found was on Michael Mattson’s thesis on Object Oriented Frameworks: a survey on methodological issues.

At last! The origin of the term, or at least the point at which is became popular. I'll quote the same paragraph from the thesis that Stefano did:

The major difference between an object-oriented framework and a class library is that the framework calls the application code. Normally the application code calls the class library. This inversion of control is sometimes named the Hollywood principle, “Do not call us, we call You”.

Which brings things back full-circle to the start, because this certainly matches my understanding of things. What I fail to understand is how you get from this quote to the military chain of command point of view.

Stefano continues (emphasis added):

Now it seems that IoC is receiving attention from the design pattern intelligentia (sic): Martin Fowler renames it Dependency Injection, and, in my opinion, misses the point: IoC is about enforcing isolation, not about injecting dependencies.

I think this is really the crux of the issue. I think there is a massive leap being made to get to any claim that IoC is about enforcing isolation. I don't think the previous uses of the term imply this at all. Certainly not the quoted thesis.

Doing some more digging, there may be some justification from John Vlissides column Protection, Part I: The Hollywood Principle. The column describes a C++ object-oriented design for a filesystem that has some protection and enforcement. (As a side note the idea of providing any level of protection enforcement through language mechanisms is abhorrent, but lets just accept that this is a desirable thing for the moment.) In any case the pertinent quote for me is:

The Template Method pattern leads to an inversion of control known as the "Hollywood Principle," or, "Don't call us; we'll call you."

The inversion of control is a consequence of using the Template Method pattern, which may themselves have something to say about enforcing some isolation, but IoC itself is a consequence, not an aim.

So lets recap where we are right now. We have one view of IoC which is just a simple way of what describing happens when you flip things around so that a framework calls the application, rather than an application calling the library. This isn't good or bad, it is just a way of describing some part of the a software systems design.

Secondly we have the view promoted by originally it would seem promoted by Stefan, but subsequently repeated in many places, where IoC is a design principle, with an explicit goal of enforcing isolation.

I find it hard to want to use IoC as a design principle. We already have a well established term for a design principle that is all about isolation: separation of concern. Which goes back to Dijkstra a good forty or so years ago.

Given this, I think IoC should only be used to describe an aspect of design where the flow of control is inverted when compared to the traditional architecture. If I can be so bold, this is the correct definition. Other definitions are wrong!

(And just to be clear, there is nothing wrong with dependency injection, it's a great way of structuring code to make it more reusable, just don't call it inversion of control!

blog comments powered by Disqus