Composing Two Functions
Composition applies one function to the result of another. The first result must satisfy the next function's input contract.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Follow the representations
A parser can turn "12" into 12. A percentage computation can map it to 0.12. A resulting string or an omitted value has different behavior, so state the accepted intermediate representation. Program transformations are easier to debug when the steps have names.
Check one failure per step
The parser rejects "x", and the percentage rule in this example can reject a numeric value over one hundred. Test both because they stop at different steps. Preconditions explain what each stage is allowed to assume.[1][2]
Check domains where the functions meet
Suppose a measurement arrives as text, a parser returns an integer centimetre reading, and a converter divides the integer by one hundred to give metres. On "250" the composition produces 2.5. Passing the raw text directly to the converter violates its input contract, even though both functions are individually valid. Write each intermediate type and unit next to the composition. For changes in order, check whether the intermediate result still satisfies the next function's requirements. See values with units.
Preserve each failure's useful meaning
A parse can fail for "twenty" while a range check can reject the successfully parsed value \(-5\). A composed interface may produce one error representation with different reasons so callers can respond appropriately. An intermediate failure should prevent subsequent steps from working on a placeholder unless recovery is explicitly part of the design. Test one input for each boundary and a successful input that exercises every stage. See error results and exceptions.