Keep Decision Functions Predictable and Repeatable
Scenario
Compare two ways of checking whether a room is open during campus hours (08:00–20:00).
Try it yourself
Choose each design and predict whether tests will pass reliably at midnight.
| Case | Result |
|---|---|
| Function reads system clock Date.now() internally | Select a choice above to see what happens. |
| Function reads and mutates a shared global freeSeats variable | Select a choice above to see what happens. |
| isOpenAt(hour) takes hour explicitly and mutates nothing | Select a choice above to see what happens. |
Reveal the explanation
- Function reads system clock Date.now() internally
Flaky! Tests pass at 14:00 and mysteriously fail at 22:00 without any code change.
- Function reads and mutates a shared global freeSeats variable
Order-dependent! Running Test B before Test A changes the outcome.
- isOpenAt(hour) takes hour explicitly and mutates nothing
Pure and deterministic. isOpenAt(14) is always true and isOpenAt(22) is always false.
Pass clocks, limits, and counts in as explicit parameters. Pure functions make repeatable fixtures trivial to run anywhere, including CI.
Your turn
Convert "canBorrowToday()" which reads the hidden global currentDay into a pure function signature and write 2 deterministic tests.
Common mistake Leaving a hidden global read inside the function while claiming the test is repeatable.
Check your work
canBorrowOnDay(dayName); canBorrowOnDay("Monday") -> true, canBorrowOnDay("Sunday") -> false.
Quick check
This browser could not save your progress. Changes last until you leave the page.