A callback, function object, function pointer, or delegate is a value which represents a subroutine and is passed from one bit of code to another, in the process being assigned to a different variable. This is accomplished in different ways across languages:
- Lisp, JavaScript, and Python functions are first-class values, which in the latter two makes them objects.
- C and C++ simply apply the concept of a pointer to functions.
- Visual Basic uses the Delegate modifier to allow the use of a Sub procedure as a type.
- Java performs reflection via a section of its standard library, which may be clumsily used to find and call a method whose name is in a string.
- PHP provides anonymous functions and a small "Function Handling" API, a much simpler implementation of reflection than that of Java.
Callbacks are used in cases where some of the logic is specified in user code, such as event-handling. Normally the callback is written within user code and passed as an argument to a library function, but sometimes a callback will instead be returned from a function for user code to call (or not) when appropriate.
For example, given the following filter function in pseudocode:
list filter(list l, delegate f)
initialize list r
for i = 0 to l.count - 1
if f.invoke(l[i]) = true then r.add l[i]
return r
We can put in any type of filtering method that we like to pass to the function. For example, given a function that will return true if the passed number is greater than 9:
boolean gr(int x)
return x > 9
You can use this to get all numbers greater than 9 on the list:
// given a list somelist delegate pfilter = reference to gr list result = filter(somelist, pfilter)