Functions That Modify Their Inputs
Some functions update the objects supplied to them. Their contracts should say which objects change and which result the caller can use.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Track aliases
Passing a list to an append operation changes the shared list. Any other variable holding that object observes the addition. A routine that builds a new list can return the additional element without changing the original. Names and objects explain why both outcomes can use the same parameter syntax.
Check before and after
With an original list of two entries, verify its length as well as the returned list's length. If nested contents may change, a shallow copy in the test can share the very object you intended to compare.[1][2]
Trace the result and the changed state separately
Suppose take_next(queue) removes the first item from [5, 9] and returns five. Its output and the resulting queue [9] are separate observations. Substituting peek_next(queue) can leave the output identical for one call while breaking the next call, since five still sits at the head. Test a second operation to expose the difference and define what happens to an empty queue. The contracts for sequence-based queues provide a concrete comparison.
Decide where an operation can leave partial work
Imagine a helper mutates two collections, removing a work item from pending and appending it to complete. A failure between the two operations loses the record from both. Reversing the order can temporarily place it in both. If they are persistent tables, a transaction can make the change atomic under the chosen isolation rules. For a local transformation, building the result before publishing it may be sufficient. See ownership of function inputs to decide which objects the caller can still observe.