Inversion of control
![]() | This article may be too technical for most readers to understand.(May 2023) |
In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. The term "inversion" is historical : a software architecture with this design "inverts" control as compared to procedural programming. In procedural programming, the code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the framework that calls into the custom, or task-specific, code.
Inversion of Control has been widely used by application development frameworks since the rise of GUI environments[1][2] and continues to be used both in GUI environments and in web server application frameworks.
Event-driven programming is often implemented using IoC so that the custom code need only be concerned with the handling of events, while the event loop 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.
Inversion of control is used to increase modularity of the program and make it extensible,[3]. The term was used by Michael Mattsson in a thesis,[4] taken from there[5] by Stefano Mazzocchi and popularized by him in 1999 in a defunct Apache Software Foundation project, Avalon, then further popularized in 2004 by Robert C. Martin and Martin Fowler.
Overview[edit]
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.[6] 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 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 that knows common behavioral and graphical elements, such as windowing systems, menus, controlling the mouse, and so on. 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, schedulers, event loops, dependency injection, and the template method are examples of design patterns that follow the inversion of control principle, although the term is most commonly used in the context of object-oriented programming.
Inversion of control serves the following design purposes:
- To decouple the execution of a task from implementation.
- To focus a module on the task it is designed for.
- To free modules from assumptions about how other systems do what they do and instead rely on contracts.
- To prevent side effects when replacing a module.
Inversion of control is sometimes referred to as the "Hollywood Principle: Don't call us, we'll call you".[1]
Background[edit]
Inversion of control is not a new term in computer science. Martin Fowler traces the etymology of the phrase back to 1988,[7] but it is closely related to the concept of program inversion described by Michael Jackson in his Jackson Structured Programming methodology in the 1970s.[8] 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.
Description[edit]
In traditional programming, the flow of the business logic 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 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 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 using static analysis. While described in terms of object interaction here, the principle can apply to other programming methodologies besides object-oriented programming.
In order for the running program to bind objects to one another, the objects must possess compatible interfaces. 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[edit]
- The Mesa Programming environment for XDE, 1985[1]
- Visual_Basic_(classic), 1991.
- HTML DOM_event
- The Spring_Framework[9]
- ASP.NET_Core[10]
- Template_method_pattern
Example Code[edit]
HTML DOM events[edit]
Web browsers implement inversion of control for DOM events in HTML. The application developer uses document.addEventListener()
to register a callback.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Level 2</title>
</head>
<body>
<h1>DOM Level 2 Event handler</h1>
<p><large><span id="output"></span></large></p>
<script>
var registeredListener = function () {
document.getElementById("output").innerHTML = "<large>The registered listener was called.</large>";
}
document.addEventListener( "click", registeredListener, true );
document.getElementById("output").innerHTML = "<large>The event handler has been registered. If you click the page, your web browser will call the event handler.</large>"
</script>
</body>
</html>
Web application frameworks[edit]
This example code for an Asp.NetCore web application creates an web application host, registers an endpoint, and then passes control to the framework:[10]
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
See also[edit]
- Abstraction layer
- Archetype pattern
- Asynchronous I/O
- Aspect-oriented programming
- Callback (computer science)
- Closure (computer science)
- Continuation
- Delegate (CLI)
- Dependency inversion principle
- Flow-based programming
- Implicit invocation
- Interrupt handler
- Message Passing
- Monad (functional programming)
- Observer pattern
- Publish/subscribe
- Service locator pattern
- Signal (computing)
- Software framework
- Strategy pattern
- User exit
- Visitor pattern
- XSLT
References[edit]
- ^ a b c Sweet, Richard (25 June 1985). "The Mesa Programming Environment". ACM SIGPLAN Notices. 20 (7).
- ^ Visual_Basic_(classic)
- ^ Johnson, Ralph E.; Foote, Brian (June–July 1988). "Designing Reusable Classes". Journal of Object-Oriented Programming. 1 (2): 22–35. CiteSeerX 10.1.1.101.8594. Retrieved 29 April 2014.
- ^ Mattsson, Michael (February 1996). "Object-Oriented Frameworks, A survey of methodological issues". Department of Computer Science, Lund University. CiteSeerX 10.1.1.36.1424. LU-CS-TR: 96-167.
- ^ Stefano Mazzocchi (22 January 2004). "On Inversion of Control". Archived from the original on 2 February 2004.
- ^ Dependency Injection.
- ^ Inversion of Control on Martin Fowler's Bliki
- ^ "Introduction to Jackson Design Method" (PDF).
- ^ "Spring Framework The IoC container". "docs.spring.io". Retrieved 25 May 2023.
- ^ a b "Ryan Nowak, Kirk Larkin, Rick Anderson". ""Routing in ASP.Net Core"". "learn.microsoft.com". microsoft. Retrieved 25 May 2023.
Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints. Endpoints are the app's units of executable request-handling code. Endpoints are defined in the app and configured when the app starts.
{{cite web}}
: CS1 maint: multiple names: authors list (link)