Keeping Conditions Free of Surprising Effects
A condition is easier to move and combine when its evaluation reads stable input and has no surprising state changes.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Predict the repeated question
A check called has_next normally reports whether another item can be read. If it actually removes the next item, testing it and then reading again skips one. Predicate functions should expose that distinction through their documented behavior and names.
Move work out of the test
Read one record into a local binding, then check explicitly for the end marker. Use that same record for processing. A trace of evaluation order confirms that each loop step has one read and that diagnostics can inspect the consumed value.[1][2]
Trace a predicate that consumes its own input
Imagine a function called has_more that removes a job from a queue while checking whether one exists. A loop may call it before retrieving a job and then retrieve the following job, skipping the value removed by the test. A separate operation can read once and hand the current job to a pure decision checking whether it is an end marker. Write the queue after each call to see where a value was consumed. See observing side effects.
Test the right kind of stability
Reusing a predicate result can be valid when the inputs and observed state stay fixed. A condition consulting a clock or shared queue can change between calls even if it writes nothing. If one observation should govern an operation, retain it explicitly rather than ask the source repeatedly. Naming intermediates explains that timing.
For an ordinary assertion, call a pure predicate twice on the same fixture and verify both equal results and unchanged inputs. Then test the separate retrieval operation's effects. This makes it clear which call owns the change and lets a later refactor move the check without altering the program.