Inversion of control
   HOME

TheInfoList



OR:

In
software engineering Software engineering is a branch of both computer science and engineering focused on designing, developing, testing, and maintaining Application software, software applications. It involves applying engineering design process, engineering principl ...
, inversion of control (IoC) is a design principle in which custom-written portions of a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to Execution (computing), execute. It is one component of software, which also includes software documentation, documentation and other intangibl ...
receive the flow of control from an external source (e.g. a framework). The term "inversion" is historical: a
software architecture Software architecture is the set of structures needed to reason about a software system and the discipline of creating such structures and systems. Each structure comprises software elements, relations among them, and properties of both elements a ...
with this design "inverts" control as compared to
procedural programming Procedural programming is a programming paradigm, classified as imperative programming, that involves implementing the behavior of a computer program as Function (computer programming), procedures (a.k.a. functions, subroutines) that call each o ...
. In procedural programming, a program's custom code calls reusable libraries to take care of generic tasks, but with inversion of control, it is the external code or framework that is in control and calls the custom code. Inversion of control has been widely used by application development frameworks since the rise of GUI environments and continues to be used both in GUI environments and in web server application frameworks. Inversion of control makes the framework extensible by the methods defined by the application programmer.
Event-driven programming In computer programming, event-driven programming is a programming paradigm in which the Control flow, flow of the program is determined by external Event (computing), events. User interface, UI events from computer mouse, mice, computer keyboard, ...
is often implemented using IoC so that the custom code need only be concerned with the handling of events, while the
event loop In computer science, the event loop (also known as message dispatcher, message loop, message pump, or run loop) is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by m ...
and dispatch of events/messages is handled by the framework or the runtime environment. In web server application frameworks, dispatch is usually called routing, and handlers may be called endpoints.


Alternative meaning

The phrase "inversion of control" has separately also come to be used in the community of Java programmers to refer specifically to the patterns of
dependency injection In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the con ...
(passing services to objects that need them) that occur with "IoC containers" in Java frameworks such as the Spring Framework. In this different sense, "inversion of control" refers to granting the framework control over the implementations of dependencies that are used by application objects rather than to the original meaning of granting the framework
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
(control over the time of execution of application code, e.g. callbacks).


Overview

As an example, with traditional programming, the main function of an application might make function calls into a menu library to display a list of available commands and query the user to select one.Dependency Injection
The library thus would return the chosen option as the value of the function call, and the main function uses this value to execute the associated command. This style was common in text-based interfaces. For example, an
email client An email client, email reader or, more formally, message user agent (MUA) or mail user agent is a computer program used to access and manage a user's email. A web application which provides message management, composition, and reception functio ...
may show a screen with commands to load new mail, answer the current mail, create new mail, etc., and the program execution would block until the user presses a key to select a command. With inversion of control, on the other hand, the program would be written using a
software framework In computer programming, a software framework is a software abstraction that provides generic functionality which developers can extend with custom code to create applications. It establishes a standard foundation for building and deploying soft ...
that knows common behavioral and graphical elements, such as windowing systems, menus, controlling the mouse, and toolbars. The custom code "fills in the blanks" for the framework, such as supplying a table of menu items and registering a code subroutine for each item, but it is the framework that monitors the user's actions and invokes the subroutine when a menu item is selected. In the mail client example, the framework could follow both the keyboard and mouse inputs and call the command invoked by the user by either means and at the same time monitor the network interface to find out if new messages arrive and refresh the screen when some network activity is detected. The same framework could be used as the skeleton for a spreadsheet program or a text editor. Conversely, the framework knows nothing about Web browsers, spreadsheets, or text editors; implementing their functionality takes custom code. Inversion of control carries the strong connotation that the reusable code and the problem-specific code are developed independently even though they operate together in an application. Callbacks,
scheduler A schedule (, ) or a timetable, as a basic time-management tool, consists of a list of times at which possible tasks, events, or actions are intended to take place, or of a sequence of events in the chronological order in which such things ...
s,
event loop In computer science, the event loop (also known as message dispatcher, message loop, message pump, or run loop) is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by m ...
s, and the template method are examples of
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" ...
s that follow the inversion of control principle, although the term is most commonly used in the context of
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
. (
Dependency injection In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the con ...
is an example of the separate, specific idea of "inverting control over the implementations of dependencies" popularised by Java frameworks.) Inversion of control is sometimes referred to as the "Hollywood Principle: Don't call us, we'll call you," reflecting how frameworks dictate execution flow.


Background

Inversion of control is not a new term in computer science. Martin Fowler traces the etymology of the phrase back to 1988,Inversion of Control
on Martin Fowler's Bliki
but it is closely related to the concept of program inversion described by
Michael Jackson Michael Joseph Jackson (August 29, 1958 – June 25, 2009) was an American singer, songwriter, dancer, and philanthropist. Dubbed the "King of Pop", he is regarded as Cultural impact of Michael Jackson, one of the most culturally significan ...
in his
Jackson Structured Programming Jackson structured programming (JSP) is a method for structured programming developed by British software consultant Michael A. Jackson (computer scientist), Michael A. Jackson and was described in his 1975 book ''Principles of Program Design''.. ...
methodology in the 1970s. A bottom-up parser can be seen as an inversion of a top-down parser: in the one case, the control lies with the parser, while in the other case, it lies with the receiving application. The term was used by Michael Mattsson in a thesis (with its original meaning of a framework calling application code instead of vice versa) and was then taken from there by Stefano Mazzocchi and popularized by him in 1999 in a defunct Apache Software Foundation project, Avalon, in which it referred to a parent object passing in a child object's dependencies in addition to controlling execution flow. The phrase was further popularized in 2004 by Robert C. Martin and Martin Fowler, the latter of whom traces the term's origins to the 1980s.


Description

In traditional programming, the flow of the
business logic In computer software, business logic or domain logic is the part of the program that encodes the real-world business rules that determine how data can be created, stored, and changed. It is contrasted with the remainder of the software that might ...
is determined by objects that are statically bound to one another. With inversion of control, the flow depends on the object graph that is built up during program execution. Such a dynamic flow is made possible by object interactions that are defined through abstractions. This run-time binding is achieved by mechanisms such as
dependency injection In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the con ...
or a service locator. In IoC, the code could also be linked statically during compilation, but finding the code to execute by reading its description from external configuration instead of with a direct reference in the code itself. In dependency injection, a dependent
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
or module is coupled to the object it needs at run time. Which particular object will satisfy the dependency during program execution typically cannot be known at
compile time In computer science, compile time (or compile-time) describes the time window during which a language's statements are converted into binary instructions for the processor to execute. The term is used as an adjective to describe concepts relat ...
using
static analysis Static analysis, static projection, or static scoring is a simplified analysis wherein the effect of an immediate change to a system is calculated without regard to the longer-term response of the system to that change. If the short-term effect i ...
. While described in terms of object interaction here, the principle can apply to other programming methodologies besides
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
. In order for the running program to bind objects to one another, the objects must possess compatible
interfaces Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inter ...
. For example, class A may delegate behavior to interface I which is implemented by class B; the program instantiates A and B, and then injects B into A.


Use

* The
Mesa A mesa is an isolated, flat-topped elevation, ridge, or hill, bounded from all sides by steep escarpments and standing distinctly above a surrounding plain. Mesas consist of flat-lying soft sedimentary rocks, such as shales, capped by a ...
Programming environment for XDE, 1985 *
Visual Basic (classic) Visual Basic (VB), sometimes referred to as Classic Visual Basic, is a third-generation programming language, third-generation programming language based on BASIC, as well as an associated integrated development environment (IDE). Visual Basic ...
, 1991. * HTML DOM event * The Spring Framework * ASP.NET Core *
Template method pattern In object-oriented programming, the template method is one of the behavioral pattern, behavioral Software design pattern, design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclas ...


Example code


HTML DOM events

Web browsers implement inversion of control for DOM events in HTML. The application developer uses to register a callback. DOM Level 2

DOM Level 2 Event handler


Web application frameworks

This example code for an ASP.NET Core web application creates a web application host, registers an endpoint, and then passes control to the framework: var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run();


See also

*
Abstraction layer In computing, an abstraction layer or abstraction level is a way of hiding the working details of a subsystem. Examples of software models that use layers of abstraction include the OSI model for network protocols, OpenGL, and other graphics libra ...
* Archetype pattern *
Asynchronous I/O In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the I/O operation has finished. A name used for asynchronous I/O in the Windows API is '' over ...
*
Aspect-oriented programming In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding behavior to existing code (an advice) ''without'' modifying t ...
*
Callback (computer science) In computer programming, a callback is a Function (computer programming), function that is stored as data (a Reference (computer science), reference) and designed to be called by another function often ''back'' to the original Abstraction (com ...
*
Closure (computer science) In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function to ...
*
Continuation In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computat ...
*
Delegate (CLI) A delegate is a form of type-safe function pointer used by the Common Language Infrastructure (CLI). Delegates specify a method to call and optionally an object to call the method on. Delegates are used, among other things, to implement callbacks ...
* Dependency inversion principle * Flow-based programming * Implicit invocation *
Interrupt handler In computer systems programming, an interrupt handler, also known as an interrupt service routine (ISR), is a special block of code associated with a specific interrupt condition. Interrupt handlers are initiated by hardware interrupts, software ...
*
Message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
*
Monad (functional programming) In functional programming, monads are a way to structure computations as a sequence of steps, where each step not only produces a value but also some extra information about the computation, such as a potential failure, non-determinism, or side e ...
*
Observer pattern In software design and software engineering, the observer pattern is a software design pattern in which an object, called the ''subject'' (also known as ''event source'' or ''event stream''), maintains a list of its dependents, called observers (a ...
*
Publish–subscribe pattern In software architecture, the publish–subscribe pattern (pub/sub) is a messaging pattern in which message senders, called publishers, categorize messages into classes (or ''topics''), and send them without needing to know which components ...
*
Service locator pattern The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator", which ...
*
Signal (computing) Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-comp ...
*
Software framework In computer programming, a software framework is a software abstraction that provides generic functionality which developers can extend with custom code to create applications. It establishes a standard foundation for building and deploying soft ...
* Strategy pattern * User exit * Visitor pattern *
XSLT XSLT (Extensible Stylesheet Language Transformations) is a language originally designed for transforming XML documents into other XML documents, or other formats such as HTML for web pages, plain text, or XSL Formatting Objects. These formats c ...


References


External links


Inversion of Control explanation and implementation example

Inversion of Control
{{DEFAULTSORT:Inversion of control Software architecture Architectural pattern (computer science) Programming principles Component-based software engineering Software design patterns