Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@alan-andrade
Last active July 25, 2017 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alan-andrade/57f2aaeba7d385cf70a05ac91aa37599 to your computer and use it in GitHub Desktop.
Save alan-andrade/57f2aaeba7d385cf70a05ac91aa37599 to your computer and use it in GitHub Desktop.
Inversion Of Control

The term Inversion of control started to be used when programming started to do UI applications.

print "What's your name?"
var name = READLINE()

The control relies on the user for the program to continue.

On UI, the code has to be always running and be ready to react when the user taps the screen.

var popup = PopupViewController()
popup.confirmationBlock = {
  // do stuff
}

// control keeps going without stopping for user actions.
return popup

Inversion of control can also be put into the perspective of WHO or WHAT is in charge of building objects / dependencies ?

class XCode {
var codeHighlighter: XCodeTextHighlighter

    init() {
      self.codeHightligher = XCodeTextHighlighter()
    }
}

In this example, the class XCode has the control of instantiating the code highlighter dependency. Inverting control means that this class isn't responsible of building the object, it can just receive it.

class XCode {
  var codeHighlighter: XCodeTextHighlighter

  init(highlighter: XCodeHighlither) {
    self.codeHightligher = highlighter
  }
}

Moreover, this practice is promoting the Single Responsibility Principle.

So in general, Dependency injection is one form of the broader technique of inversion of control.

image

Wikipedia:

In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. [1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

Dependency injection is one form of the broader technique of inversion of control. Rather than low level code calling up to high level code, high level code can receive lower level code that it can call down to. This inverts the typical control pattern seen in procedural programming.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment