Who Owns a Function Input
A caller and function can share an input object, transfer its use by convention, or choose an independent copy. Each choice has observable consequences.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Define who can mutate
A sorting helper consuming a caller's buffer can reorder it in place if that is promised. Another caller may need the source order for display. A contract on mutation lets the author decide whether to retain a copy first.
Choose the necessary depth
For sortable rows containing lists of notes, copying the outer collection is enough to reorder rows independently. Editing a notes list requires copying that nested structure as well if it must remain isolated. Shallow copies explain the difference.[1][2]
Use an alias to test an ownership promise
Suppose the caller saves a reference to a list of coordinates and hands the list to normalize. If the contract promises preservation, both names should still show the original after normalization. Making a shallow outer copy can be insufficient when normalizing by assigning elements of an inner list. Start with [[4, 2], [7, 3]] and inspect the first inner pair after transforming. See shallow container copies.
Define when changes become observable
An explicitly in-place function can accept caller-owned storage to avoid allocating a large copy. When the third element is invalid, decide whether the first two may already be transformed. If the operation promises all-or-nothing behavior, validate the needed properties before mutating or stage the changes separately. Also consider repeat calls on the same object. Test an input with valid leading elements and a bad last element to exercise partial work. See side effects in functions.