Callback (computer science)
Encyclopedia
In computer programming
, a callback is a reference
to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer
to call a subroutine
(or function) defined in a higher-level layer.
, then writing the function so that it takes a callback makes it more flexible: its user can choose whatever hashing algorithm is desired and the function will continue to work, since it uses the callback to turn option names into hashes; thus, callbacks allow the user of a function to fine-tune it at runtime.
Another use is in error signaling. A Unix
program, for example, might not want to terminate immediately when it receives SIGTERM
; to make sure things get taken care of, it would register the cleanup function as a callback.
Callbacks may also be used to control whether a function acts or not: Xlib
allows custom predicates
to be specified to determine whether a program wishes to handle an event.
The following code in C
demonstrates the use of callbacks to display two numbers.
This should provide output similar to:
125185 and 89188225
9084 and 9441
42 and 42
Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions (not shown in the above example). This allows correct information hiding
: the code that passes a callback to a calling function does not need to know anything about the parameters that will be passed to them. If it only passed the return value, then the parameters would need to be exposed publicly.
This information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data.
s.
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
, a callback is a reference
Reference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...
to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer
Abstraction layer
An abstraction layer is a way of hiding the implementation details of a particular set of functionality...
to call a subroutine
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
(or function) defined in a higher-level layer.
Use
Callbacks have a wide variety of uses. For example, imagine a function that reads a configuration file and associates values with options. If the options are identified by a hashHash function
A hash function is any algorithm or subroutine that maps large data sets to smaller data sets, called keys. For example, a single integer can serve as an index to an array...
, then writing the function so that it takes a callback makes it more flexible: its user can choose whatever hashing algorithm is desired and the function will continue to work, since it uses the callback to turn option names into hashes; thus, callbacks allow the user of a function to fine-tune it at runtime.
Another use is in error signaling. A Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...
program, for example, might not want to terminate immediately when it receives SIGTERM
SIGTERM
On POSIX-compliant platforms, SIGTERM is the signal sent to a process to request its termination. The symbolic constant for SIGTERM is defined in the header file signal.h. Symbolic signal names are used because signal numbers can vary across platforms, however on the vast majority of systems,...
; to make sure things get taken care of, it would register the cleanup function as a callback.
Callbacks may also be used to control whether a function acts or not: Xlib
Xlib
Xlib is an X Window System protocol client library written in the C programming language. It contains functions for interacting with an X server. These functions allow programmers to write programs without knowing the details of the protocol...
allows custom predicates
Branch predication
Branch predication is a strategy in computer architecture design for mitigating the costs usually associated with conditional branches, particularly branches to short sections of code...
to be specified to determine whether a program wishes to handle an event.
The following code in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
demonstrates the use of callbacks to display two numbers.
This should provide output similar to:
125185 and 89188225
9084 and 9441
42 and 42
Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions (not shown in the above example). This allows correct information hiding
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...
: the code that passes a callback to a calling function does not need to know anything about the parameters that will be passed to them. If it only passed the return value, then the parameters would need to be exposed publicly.
This information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data.
Implementation
The form of a callback varies among programming languageProgramming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s.
- CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
and PascalPascal (programming language)Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
allow function pointerFunction pointerA function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...
s as arguments to other functions. Other languages, such as JavaScriptJavaScriptJavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
, PythonPython (programming language)Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
and PHPPHPPHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
, simply allow the name of a function or a function literal (lambda expression) to be passed through. - The .NET Framework.NET FrameworkThe .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
, used in languages such as C# and VB.NET, provides a type-safeType safetyIn computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behaviour caused by a discrepancy between differing data types...
encapsulating reference, a 'delegateDelegate (.NET)A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners....
', to define well-typed function pointerFunction pointerA function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...
s. These can be used as callbacks. - Events and event handlers, as used in .NET languages, provide generalized syntax for callbacks.
- Functional languages generally support first-class functions, which can be passed as callbacks to other functions, stored as data or returned from functions.
- Some languages, such as Algol 68ALGOL 68ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...
, PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, SmalltalkSmalltalkSmalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code (lambda expressionLambda expressionLambda expression may refer to:*Anonymous function*Lambda calculus#Definition...
s) to be supplied instead of references to functions defined elsewhere. - In some languages, e.g. Scheme, ML, JavaScriptJavaScriptJavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
, PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, SmalltalkSmalltalkSmalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, PHPPHPPHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
(since 5.3.0), and many others, such functions can be closuresClosure (computer science)In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
, i.e. they can access and modify variables locally defined in the context in which the function was defined. - In object-oriented programmingObject-oriented programmingObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
languages without function-valued arguments, such as JavaJava (programming language)Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate. They are useful in implementing various design patterns such as VisitorVisitor patternIn 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 existing object structures without modifying those...
, ObserverObserver patternThe observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods...
, and StrategyStrategy patternIn computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable...
. - C++ allows objects to provide their own implementation of the function call operation. The Standard Template LibraryStandard Template LibraryThe Standard Template Library is a C++ software library which later evolved into the C++ Standard Library. It provides four components called algorithms, containers, functors, and iterators. More specifically, the C++ Standard Library is based on the STL published by SGI. Both include some...
accepts these objects (called functorsFunction objectA function object, also called a functor, functional, or functionoid, is a computer programming construct allowing an object to be invoked or called as though it were an ordinary function, usually with the same syntax.-Description:...
), as well as function pointers, as parameters to various polymorphic algorithms
See also
- Continuation-passing styleContinuation-passing styleIn functional programming, continuation-passing style is a style of programming in which control is passed explicitly in the form of a continuation. Gerald Jay Sussman and Guy L. Steele, Jr...
- Signals and slotsSignals and slotsSignals and slots is a language construct introduced in Qt, which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that controls can send signals containing event information Signals and slots is a language construct introduced in Qt, which makes it...
- Event-driven programmingEvent-driven programmingIn computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions or messages from other programs or threads.Event-driven programming can also be defined as an...
- libsigc++Libsigc++Libsigc++ is a C++ library for typesafe callbacks.'libsigc++' implements a callback system for use in abstract interfaces and general programming. Libsigc++ is one of the earliest implementations of the signals and slots concept implemented using C++ template metaprogramming...
, a callback library for C++ - Implicit invocationImplicit invocationImplicit 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...
- User exitUser exitA user exit is a subroutine invoked by a software package for a predefined event in the execution of the package. Clients of the package can substitute their own subroutines in place of the default ones provided by the package vendor to provide customized functionality.A typical use is replacing...
- Inversion of controlInversion of ControlIn software engineering, Inversion of Control is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming....