Passing a Function as a Callback
A callback is an operation supplied to another procedure to perform a defined part of that procedure's work.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Separate the traversal from the rule
A collection scan may receive a callback extracting each object's score. Given two records labeled low and high with scores 3 and 9, the same traversal compares the scores without needing to know how they are stored. Predicate functions are a common kind of callback for a selection operation.
Specify how often it runs
A reporting callback that writes a line behaves differently if a sorting helper invokes it repeatedly. Document call timing and constraints before passing a callback with side effects.[1][2]
Observe the order and the arguments of calls
A parser receives records numbered one through four and calls an observer only for rejected records. With invalid records two and four, a recording observer should see [(2, reason_a), (4, reason_b)] in that order if the parser's interface promises input order. An observer attached before validation might see all four records or incomplete reasons. Decide whether emitted records are snapshots or mutable references that later processing can alter. See ownership of a function input.
Document what happens when the callback fails
A display hook may be incidental to the computation. A callback that durably saves each rejected record is essential to an audit. Catching every callback exception would make those designs behave alike even though their failure requirements differ. Test with a callback that succeeds once and fails on its second call. Check the visible sequence of events and whether the parser reports how far it got. See functions with visible side effects.