Writing Predicates as Functions
A predicate gives a name to a question that evaluates to true or false for a documented class of inputs.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Name the question
A stock check can compute whether a requested count is positive and no greater than the available count. Call it can_reserve. This gives callers a function contract for interpreting a true answer and keeps the rule together in one place.
Exercise the zero case
With availability five, requests of five, six, and zero yield true, false, and false. A poorly designed predicate may accept zero when it checks only the upper bound. Keep reserving stock as a separate operation so observing side effects remains predictable for callers.[1][2]
Name a domain question whose answer remains readable
A function can answer whether a workshop can accept a reservation using requested and available seat counts. With requested two and available three, the predicate is true. With requested four and available three, it is false. With requested zero, it should be false if a positive request is required. Writing that example in the function contract prevents a reader from guessing whether “can reserve” checks only capacity or valid quantity as well.
Keep the reported answer and any reservation separate
A predicate is easier to reuse when evaluating it does not itself reserve seats or consume a job. A page can ask it to display eligibility, and a submission can use a separate operation to attempt the write under up-to-date rules. If system state can change between those steps, the write needs its own check. Observable side effects explain why a true flag alone does not establish a later change.
Use a table of distinct valid, invalid, and boundary values for the pure check. If a caller needs to explain a false answer, choose a richer decision result with a stable reason instead of giving different meanings to false.