HOME

TheInfoList



OR:

In
software engineering Software engineering is a systematic engineering approach to software development. A software engineer is a person who applies the principles of software engineering to design, develop, maintain, test, and evaluate computer software. The term ' ...
, inversion of control (IoC) is a
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" b ...
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 execute. Computer programs are one component of software, which also includes documentation and other intangible components. A computer progra ...
receive the flow of control from a generic framework. A
software architecture Software architecture is the fundamental structure of 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 and relations. ...
with this design inverts control as compared to traditional
procedural programming Procedural programming is a programming paradigm, derived from imperative programming, based on the concept of the '' procedure call''. Procedures (a type of routine or subroutine) simply contain a series of computational steps to be carri ...
: in traditional programming, the custom 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 is used to increase
modularity Broadly speaking, modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a s ...
of the program and make it extensible, and has applications in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
and other
programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, s ...
s. The term was used by Michael Mattsson in a thesis, taken from there by Stefano Mazzocchi and popularized by him in 1999 in a defunct Apache Software Foundation project,
Avalon Avalon (; la, Insula Avallonis; cy, Ynys Afallon, Ynys Afallach; kw, Enys Avalow; literally meaning "the isle of fruit r appletrees"; also written ''Avallon'' or ''Avilion'' among various other spellings) is a mythical island featured in th ...
, then further popularized in 2004 by Robert C. Martin and Martin Fowler. The term is related to, but different from, the dependency inversion principle, which concerns itself with decoupling dependencies between high-level and low-level layers through shared abstractions. The general concept is also related to
event-driven programming In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or message passing from other programs or th ...
in that it is often implemented using IoC so that the custom code is commonly only concerned with the handling of events, whereas the
event loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
and dispatch of events/messages is handled by the framework or the runtime environment.


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 Command may refer to: Computing * Command (computing), a statement in a computer language * COMMAND.COM, the default operating system shell and command-line interpreter for DOS * Command key, a modifier key on Apple Macintosh computer keyboards * ...
and query the user to select one. 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 an abstraction in which software, providing generic functionality, can be selectively changed by additional user-written code, thus providing application-specific software. It provides a standard ...
that knows common behavioral and graphical elements, such as
windowing system In computing, a windowing system (or window system) is software that manages separately different parts of display screens. It is a type of graphical user interface (GUI) which implements the WIMP (windows, icons, menus, pointer) paradigm for ...
s, 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 Network interface may refer to: * Network interface controller, a computer hardware component that connects a computer to a computer network * Network interface device, a device that serves as the demarcation point between a telephone carrier's loc ...
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 loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
s, dependency injection, and the
template method In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defines ...
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" b ...
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", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
. Inversion of control serves the following design purposes: * To
decouple __NOTOC__ Decoupling usually refers to the ending, removal or reverse of coupling. Decoupling may also refer to: Economics * Decoupling (advertising), the purchase of services directly from suppliers rather than via an advertising agency * Deco ...
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 A contract is a legally enforceable agreement between two or more parties that creates, defines, and governs mutual rights and obligations between them. A contract typically involves the transfer of goods, services, money, or a promise to ...
. * To prevent
side effect In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
s when replacing a module. Inversion of control is sometimes facetiously referred to as the "Hollywood Principle: Don't call us, we'll call you".


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 one of the most significant cultural figures of the 20th century. Over a ...
in his Jackson Structured Programming 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. Dependency injection is a specific type of IoC.Dependency Injection
A service locator such as the Java Naming and Directory Interface (JNDI) is similar. In an article by Loek Bergman, it is presented as an architectural principle. In an article by Robert C. Martin,The Dependency Inversion principle
by Robert C. Martin
the dependency inversion principle and abstraction by layering come together. His reason to use the term "inversion" is in comparison with traditional software development methods. He describes the decoupling of services by the abstraction of layers when he is talking about dependency inversion. The principle is used to find out where system borders are in the design of the abstraction layers.


Description

In traditional programming, the
flow Flow may refer to: Science and technology * Fluid flow, the motion of a gas or liquid * Flow (geomorphology), a type of mass wasting or slope movement in geomorphology * Flow (mathematics), a group action of the real numbers on a set * Flow (psych ...
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 In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
using static analysis. 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", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
. 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.


Implementation techniques

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, there are several basic techniques to implement inversion of control. These are: * Using a service locator pattern * Using dependency injection; for example, ** Constructor injection ** Parameter injection ** Setter injection ** Interface injection ** Method Injection * Using a contextualized lookup * Using the
template method design pattern In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defines ...
* Using the
strategy design pattern In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time ins ...
In an original article by Martin Fowler, the first three different techniques are discussed. In a description about inversion of control types,IoC Types
the last one is mentioned. Often the contextualized lookup will be accomplished using a service locator.


Examples

Most frameworks such as .NET or
Enterprise Java Jakarta EE, formerly Java Platform, Enterprise Edition (Java EE) and Java 2 Platform, Enterprise Edition (J2EE), is a set of specifications, extending Java SE with specifications for enterprise features such as distributed computing and web ser ...
display this pattern: public class ServerFacade This basic outline in Java gives an example of code following the IoC methodology. It is important, however, that in the a lot of assumptions are made about the data returned by the
data access object In software, a data access object (DAO) is a pattern that provides an abstract interface to some type of database or other persistence mechanism. By mapping application calls to the persistence layer, the DAO provides data operations without expo ...
(DAO). Although all these assumptions might be valid at some time, they couple the implementation of the to the DAO implementation. Designing the application in the manner of inversion of control would hand over the control completely to the DAO object. The code would then become public class ServerFacade The example shows that the way the method is constructed determines if IoC is used. It is the way that parameters are used that define IoC. This resembles the
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 i ...
style that some object-oriented programming languages use.


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 The archetype pattern is a software design pattern that separates logic from implementation. The separation is accomplished through the creation of two Abstract class, abstract classes: a Decorator pattern, decorator (for logic), and a delegate (f ...
*
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 transmission has finished. A name used for asynchronous I/O in the Windows API is overlap ...
*
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 ...
*
Callback (computer science) In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to ''call back'' (execute) the callback function as part of its job. Thi ...
*
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 t ...
*
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 callback ...
* Dependency inversion principle * Flow-based programming * Implicit invocation *
Interrupt handler In computer systems programming, an interrupt handler, also known as an interrupt service routine or ISR, is a special block of code associated with a specific interrupt condition. Interrupt handlers are initiated by hardware interrupts, softw ...
*
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 supporti ...
*
Monad (functional programming) In functional programming, a monad is a software design pattern with a structure that combines program fragments ( functions) and wraps their return values in a type with additional computation. In addition to defining a wrapping monadic type, mo ...
*
Observer pattern In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by ...
* Publish/subscribe * Service locator pattern *
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 an abstraction in which software, providing generic functionality, can be selectively changed by additional user-written code, thus providing application-specific software. It provides a standard ...
* 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, which may subse ...


References


External links


Inversion of Control explanation and implementation example

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