Categories
design-patterns inversion-of-control oop

What is Inversion of Control?

2187

Inversion of Control (IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. Which problem does it solve?
  3. When is it appropriate to use and when not?

6

  • 342

    The problem with most of these answers is the terminology used. What’s a container? Inversion? Dependency? Explain it in layman terms without the big words.

    Sep 16, 2010 at 1:30

  • 15

    See also on Programmers.SE: Why is Inversion of Control named that way?

    – Izkata

    Jul 22, 2013 at 20:34

  • 12

    It is Dependency Injection (DI) – see Martin Fowlers’ descrition here: martinfowler.com/articles/injection.html#InversionOfControl

    Sep 16, 2014 at 23:16

  • It is an adjective, not a noun, it not a thing, it is a description of a change made to code, where the control of flow is in the delegate, not the container.

    Aug 12, 2016 at 13:21

  • Best way to understand IOC is to hear Martin Fowler and Uncle BOB…just type IOC with the names mentioned

    Jun 11, 2018 at 12:52


1883

The Inversion-of-Control (IoC) pattern, is about providing any kind of callback (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.

Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don’t lower your product’s worth by using general term “IoC” instead).

For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor {

    private SpellChecker checker;

    public TextEditor() {
        this.checker = new SpellChecker();
    }
}

What we’ve done here creates a dependency between the TextEditor and the SpellChecker.
In an IoC scenario we would instead do something like this:

public class TextEditor {

    private IocSpellChecker checker;

    public TextEditor(IocSpellChecker checker) {
        this.checker = checker;
    }
}

In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.

In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor‘s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:

SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);

Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we’re injecting the dependency into the TextEditor signature.

34

  • 64

    Good clear example. However, suppose rather than requiring the ISpellChecker interface be passed to the object’s constructor, we exposed it as a settable property (or SetSpellChecker method). Would this still constitute IoC?

    – devios1

    Dec 20, 2008 at 2:36

  • 34

    chainguy1337 – yes it would. Using setters like that is called setter injection as opposed to constructor injection (both dependency injection techniques). IoC is a fairly generic pattern, but dependency injection acheives IoC

    Aug 29, 2009 at 1:25

  • 56

    I agree with @Rogeria. this doesn’t explain why it is called the IoC and I am surprised by the number of up votes 😉

    Dec 23, 2010 at 20:01

  • 41

    I side with @Rogerio and @Pangea. This may be a good example for constructor injection but not a good answer to the original question. IoC, as defined by Fowler, can be realised without using injection of any kind, e.g. by using a service locator or even simple inheritance.

    – mtsz

    Jul 14, 2011 at 0:49


  • 21

    The example you gave is not of IOC, it is Dependency Injection example.

    Jul 27, 2013 at 14:12

768

Inversion of Control is what you get when your program callbacks, e.g. like a gui program.

For example, in an old school menu, you might have:

print "enter your name"
read name
print "enter your address"
read address
etc...
store in database

thereby controlling the flow of user interaction.

In a GUI program or somesuch, instead we say:

when the user types in field a, store it in NAME
when the user types in field b, store it in ADDRESS
when the user clicks the save button, call StoreInDatabase

So now control is inverted… instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.

Basically, anything with an event loop, callbacks, or execute triggers falls into this category.

14

  • 186

    dont mark this guy down. technically he is correct martinfowler.com/bliki/InversionOfControl.html IoC is a very general principal. Flow of control is “inverted” by dependency injection because you have effectively delegated dependancies to some external system (e.g. IoC container)

    Aug 29, 2009 at 1:51

  • 44

    Agreed with Schneider’s comment. 5 downvotes? The mind boggles, since this is the only answer that’s really correct. Note the opening: ‘like a gui program.’ Dependency injection is only the most commonly-seen realization of IoC.

    Feb 12, 2010 at 14:45


  • 46

    Indeed, this is one of the few correct anwsers! Guys, IoC is not fundamentally about dependencies. Not at all.

    – Rogério

    Apr 2, 2010 at 14:08

  • 17

    +1 – This is a good description (with example) of the following statement by Martin Fowler – “Early user interfaces were controlled by the application program. You would have a sequence of commands like “Enter name”, “enter address”; your program would drive the prompts and pick up a response to each one. With graphical (or even screen based) UIs the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen. The main control of the program was inverted, moved away from you to the framework.”

    Oct 16, 2010 at 8:29

  • 22

    I now get it why it is sometimes facetiously referred to as the “Hollywood Principle: Don’t call us, we’ll call you”

    Nov 6, 2013 at 7:27

478

What is Inversion of Control?

If you follow these simple two steps, you have done inversion of control:

  1. Separate what-to-do part from when-to-do part.
  2. Ensure that when part knows as little as possible about what part; and vice versa.

There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.

The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!

Examples

  • Event Handling. Event Handlers (what-to-do part) — Raising Events (when-to-do part)
  • Dependency Injection. Code that constructs a dependency (what-to-do part) — instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).
  • Interfaces. Component client (when-to-do part) — Component Interface implementation (what-to-do part)
  • xUnit fixture. Setup and TearDown (what-to-do part) — xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
  • Template method design pattern. template method when-to-do part — primitive subclass implementation what-to-do part
  • DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) — COM/OS (when-to-do part)

6

  • 2

    How you are saying Interfaces. Component client (when-to-do part) as “when” does not make sense when we use interfaces ( Ex: Dependency Injection), we just abstract it out and give the client flexibility about adding any implementation but there is no “when” involved there. I agree with “when” in case of Raising Events of Event Handling.

    – OldSchool

    May 4, 2017 at 15:20

  • By ‘component client’ I meant the user / client of the interface. The client knows ‘when’ to trigger the ‘what-to-do’ part whether the intention is to extend the functionality or not.

    – rpattabi

    May 5, 2017 at 10:43

  • Take a look at this wonderful article by Martin Fowler. He shows how interfaces make the fundamental part of inversion of control: martinfowler.com/articles/injection.html#InversionOfControl

    – rpattabi

    May 5, 2017 at 10:44

  • 1

    two first sentences are brilliant. awesome !! perfect separating by when-to-do and what-to-do !! i dont know why other answers get that many of upvotes. they just talking codes without any understandings.

    Jun 5, 2018 at 18:41

  • 2

    @rpattabi, give an example in code of what you said in the answer

    Jan 23, 2019 at 16:10