Guard a Step with Its Precondition
Scenario
A university science lab lends microscopes to students. To loan a microscope safely, the desk system must look up the student's safety badge, confirm availableStock > 0, and only then subtract 1 from availableStock and print the loan slip.
Try it yourself
What goes wrong if the system subtracts 1 from availableStock before checking whether the student holds a valid safety badge?
| Case | Result |
|---|---|
| steps: [Check safetyBadge == true, Check availableStock > 0, Subtract 1 from availableStock, Print loan slip] with badge=true, stock=2 | Select a choice above to see what happens. |
| steps in safe order with badge=true, stock=0 | Select a choice above to see what happens. |
| unsafe order [Subtract 1 from availableStock, Check safetyBadge == true] with badge=false, stock=2 | Select a choice above to see what happens. |
Reveal the explanation
- steps: [Check safetyBadge == true, Check availableStock > 0, Subtract 1 from availableStock, Print loan slip] with badge=true, stock=2
Loan approved; stock becomes 1; slip printed
- steps in safe order with badge=true, stock=0
Stopped at stock check; stock remains 0 (never -1); no slip printed
- unsafe order [Subtract 1 from availableStock, Check safetyBadge == true] with badge=false, stock=2
Stock wrongly drops to 1 even though the loan is rejected
Always order a guarded sequence as: 1) Read inputs, 2) Check all preconditions, 3) Update state, 4) Confirm output. Never mutate state on a request that might still fail a check.
Download shared test cases
Your turn
Put these 4 study-room booking steps into a safe order: (A) Print door code, (B) Check studentId is active, (C) Mark room as booked, (D) Check room is free.
Common mistake Placing (C) Mark room as booked before checking (B) studentId is active or (D) room is free.
Check your work
Order B -> D -> C -> A (or D -> B -> C -> A), with both checks strictly before marking the room booked and printing the code.
Quick check
This browser could not save your progress. Changes last until you leave the page.