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. 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 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,
schedulers,
event loops, 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. (
Dependency injection 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 ==