Inversion of control
   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 program ...
receive the
flow of control 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 ''imp ...
from a generic
framework A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of. Framework may refer to: Computing * Application framework, used to implement the structure of an application for an op ...
. 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 carried ...
: 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 sy ...
of the program and make it
extensible Extensibility is a software engineering and systems design principle that provides for future growth. Extensibility is a measure of the ability to extend a system and the level of effort required to implement the extension. Extensions can be t ...
, 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 pr ...
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, suc ...
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 the ...
, then further popularized in 2004 by
Robert C. Martin Robert Cecil Martin (born 5 December 1952), colloquially called "Uncle Bob", is an American software engineer, instructor, and best-selling author. He is most recognized for developing many software design principles and for being a founder of t ...
and Martin Fowler. The term is related to, but different from, the
dependency inversion principle In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting ...
, which concerns itself with decoupling dependencies between high-level and low-level
layers Layer or layered may refer to: Arts, entertainment, and media * ''Layers'' (Kungs album) * ''Layers'' (Les McCann album) * ''Layers'' (Royce da 5'9" album) *"Layers", the title track of Royce da 5'9"'s sixth studio album *Layer, a female Maveric ...
through shared
abstractions Abstraction in its main sense is a conceptual process wherein general rules and concepts are derived from the usage and classification of specific examples, literal ("real" or "concrete") signifiers, first principles, or other methods. "An abstr ...
. 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 t ...
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 In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments. To start a program's execution, the loader or operating system passes contro ...
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. 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 interface In computing, text-based user interfaces (TUI) (alternately terminal user interfaces, to reflect a dependence upon the properties of computer terminals and not just text), is a retronym describing a type of user interface (UI) common as an e ...
s. 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 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.
Callback Callback may refer to: * Callback (comedy), a joke which refers to one previously told * Callback (computer programming), executable code that is passed as a parameter to other code * Callback (telecommunications), the telecommunications event th ...
s,
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 are i ...
s,
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 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 pr ...
. 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 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 tran ...
. * 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 Bottom-up may refer to: * Bottom-up analysis, a fundamental analysis technique in accounting and finance * Bottom-up parsing, a computer science strategy * Bottom-up processing, in Pattern recognition (psychology) * Bottom-up theories of galaxy fo ...
can be seen as an inversion of a
top-down parser Top-down parsing in computer science is a parsing strategy where one first looks at the highest level of the parse tree and works down the parse tree by using the rewriting rules of a formal grammar. LL parsers are a type of parser that uses a top-d ...
: 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 The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and resources (in the form of Java objects) via a name. Like all Java APIs that interface with host ...
(JNDI) is similar. In an article by Loek Bergman, it is presented as an architectural principle. In an article by
Robert C. Martin Robert Cecil Martin (born 5 December 1952), colloquially called "Uncle Bob", is an American software engineer, instructor, and best-selling author. He is most recognized for developing many software design principles and for being a founder of t ...
,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 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 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 ...
or module is coupled to the object it needs at
run time Run(s) or RUN may refer to: Places * Run (island), one of the Banda Islands in Indonesia * Run (stream), a stream in the Dutch province of North Brabant People * Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
. 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 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", 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 pr ...
. 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), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
. 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 pr ...
, there are several basic techniques to implement inversion of control. These are: * Using a
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", whic ...
* 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 * 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 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 ...
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 *
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 overlappe ...
*
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 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 toge ...
*
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 computati ...
*
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 In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting ...
*
Flow-based programming In computer programming, flow-based programming (FBP) is a programming paradigm that defines application software, applications as networks of "black box" process (computer science), processes, which exchange data across predefined connections by ...
*
Implicit invocation Implicit invocation is a term used by some authors for a style of software architecture in which a system is structured around event handling, using a form of callback. It is closely related to inversion of control and what is known informally a ...
*
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, softwar ...
*
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 ...
*
Monad (functional programming) In functional programming, a monad is a software design pattern with a structure that combines program fragments (Function (computer programming), functions) and wraps their return values in a Type system, type with additional computation. In add ...
*
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 ca ...
* Publish/subscribe *
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", whic ...
*
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-compl ...
*
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 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 in ...
*
User exit A user exit is a subroutine invoked by a software package for a predefined event in the execution of the package. In some cases the exit is specified by the installation when configuring the package while in other cases the users of the package can ...
*
Visitor pattern In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to ...
*
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 subseque ...


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