Callback (computer science)
|
- For a discussion of callback with computer modems, see callback (telecommunications).
In computer science, a callback is executable code that is passed as a parameter to other code. It allows a low level software layer to call a function occurring in a higher level layer. Usually the higher level code first calls a function within the lower level code passing to it a pointer or handle to another function. Then the lower level function in the course of executing may call the passed-in function any number of times to perform some subtask.
A callback can be used as a simpler alternative to polymorphism and generic programming, in that the exact behavior of a function can be dynamically determined by passing different (yet compatible) function pointers or handles to the lower level function. This can be a very powerful technique for code reuse.
Contents |
Motivation
To understand the motivation of callbacks, consider the problem of performing an arbitrary operation on each item in a list. One approach is to obtain an iterator over the list, and then operate on successive objects obtained from the iterator. This is the most common solution in practice, but it is not ideal; the code to manage the iterator must be duplicated at each point in the code where the list is traversed. Furthermore, if the list is updated by an asynchronous process, the iterator might skip over items or become corrupt during the traversal.
An alternative might be to create a new library function that performs the desired operation with appropriate synchronization. This approach still requires each new library function to contain the code to traverse the list. This solution is not acceptable for libraries intended for broad applications; the library developer cannot anticipate every application need, and the application developer should not need to know the details of the library implementation.
Callbacks solve these shortcomings. One procedure is written to traverse the list, and this procedure uses application-provided code to operate on each item. There is a clear distinction between the library and the application without sacrificing flexibility.
The following code in C demonstrates the use of callbacks for the specific case of searching an array for an item (namely, the first integer greater than 5). First, the iteration approach:
for(i = 0; i < length; i++) { if(array[i] > 5) break; } if(i < length) { printf("Item %d\n", i); } else { printf("Not found\n"); }
Next, the callback approach:
/* LIBRARY CODE */ int traverseWith(int array[], size_t length, int (*callback)(int index, int item, void *param), void *param) { int exitCode = 0; for(i = 0; i < length; i++) { exitCode = callback(i, array[i], param); if(exitCode) { break; } } return exitCode; } /* APPLICATION CODE */ int search(int index, int item, void *param) { if(item > 5) { *(int *)param = index; return 1; } else { return 0; } } /* (in another function) */ int index; int found; found = traverseWith(array, length, search, &index); if(found) { printf("Item %d\n", index); } else { printf("Not found\n"); }
In this example the callback receives an extra parameter so that it can access data from the calling scope (a form of closure). Other languages, particularly functional programming languages, can provide this access automatically. Synchronization concerns have been omitted from these examples, but they can easily be addressed in the traverseWith function. More importantly, they can be addressed, or ignored, by changing only that function.
Implementation
The form of a callback varies among programming languages.
- C and C++ allow function pointers as arguments to other functions.
- Lisp and other functional programming languages likewise allow names of functions as parameters to other functions. The programmer can also pass anonymous code as a lambda expression.
- In object-oriented programming languages, a class can have methods with behavior that is only loosely defined. Instances of this class can then be passed to library objects to provide application-specific behavior. These classes are a more structured kind of callback. They are useful in implementing various design patterns like Visitor, Observer, and Strategy.
- Some systems have built-in programming languages to support extension and adaptation. These languages provide callbacks without the need for separate software development tools.
Special cases
Callback functions are also frequently used as a means to handle exceptions arising within the low level function, as a way to enable side-effects in response to some condition, or as a way to gather operational statistics in the course of a larger computation.
A pure callback function is one which is idempotent (always returns the same value given the same inputs) and free of observable side-effects. Some uses of callbacks, such as the sorting example, require pure callback functions to operate correctly.
A special case of a callback is a called a predicate callback, or just predicate for short. This is a pure callback function which accepts a single input value and returns a Boolean value. These types of callbacks are useful for filtering collections of values by some condition.
Many object-oriented programming languages allow the use of function objects (also known as functors) as an alternate way of expressing a callback function. Most functional programming languages use callbacks as a primary method of computing, in that functions are treated as first-class objects.
See also
- libsigc++ - Callback Framework for C++
- Interceptor
External links
- Style Case Study #2: Generic Callbacks (http://gotw.ca/gotw/083.htm)
- The C++ callback framework (http://embedding.net/eSOAP/english/datasheet/callback.html)
- Basic Instincts: Implementing Callback Notifications Using Delegates (http://msdn.microsoft.com/msdnmag/issues/02/12/basicinstincts)
- Implement Script Callback Framework in ASP.NET (http://www.codeproject.com/aspnet/ScriptCallbackFramework.asp)
- Callback Balance C++ net framework (http://www.stargeek.com/item/91792.html)
- Callback Procedures (http://www.itspecial.org/1cd_dlg.htm#Callback)
- C++ Callback Solution (http://partow.net/programming/templatecallback/index.html)
- Citations from CiteSeer (http://citeseer.ist.psu.edu/cis?q=callback)