Designing a Function with Multiple Input Forms
An interface accepting several forms needs an explicit decision about ambiguous values, conversion, and how effects depend on the chosen form.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Try a string input
A summary routine may accept one label or a collection of labels. Python strings are iterable, so accidentally sending "yes" through a generic iterable branch may yield labels y, e, and s. Types and operations identify where that assumption enters.
Normalize once
The routine can wrap a single accepted label in a collection first, then use the normal shared path. Test one label, multiple labels, and an empty list. Document which interpretations are valid in the function contract.[1][2]
Choose examples that make accepted forms unambiguous
A duration converter could accept an integer number of seconds, or a quantity and explicit unit. With these rules duration(90) and duration(1.5, "min") both represent ninety seconds. An ambiguous duration("90") needs a decision about strings, including whitespace and invalid units. Consider a pair of separately named constructors when their accepted inputs or error policies grow apart. See coercion and explicit conversion.
Resolve inputs into one internal representation
Once conversion succeeds, the underlying duration can be stored in a defined unit such as milliseconds with a stated rounding rule. Test fractional values below one millisecond and negative values according to the domain. Running shared tests through both entry forms can reveal divergent rounding or validation. Do not let an overload intended for scalar input inadvertently accept an iterable character by character. See values with units for why the stored unit is part of the invariant.