Record the State Before and After an Action
Scenario
Study Room B starts with freeSeats = 1. Two students submit booking requests in sequence.
- 1Initial state before requests
- 2Request 1 arrives (valid)
- 3Request 2 arrives (room now full)
Try it yourself
Step through both requests and predict freeSeats after each one.
| Case | State after the step |
|---|---|
| Initial state before requests | — |
| Request 1 arrives (valid) | — |
| Request 2 arrives (room now full) | — |
Reveal the explanation
- Initial state before requests
Room B has freeSeats = 1.
- Request 1 arrives (valid)
Decision: Accept. Stored state updates to freeSeats = 0.
- Request 2 arrives (room now full)
Decision: Decline. Stored state remains freeSeats = 0 (never becomes -1).
Always check that a declined request leaves state untouched. Subtracting a seat on a declined request creates impossible negative state.
Your turn
Trace a library reader starting at borrowed = 2 through two consecutive checkout requests for available books.
Common mistake Incrementing borrowed count even when the second request is declined at the limit.
Check your work
After request 1: Accept, borrowed = 3. After request 2: Decline, borrowed stays 3.
Quick check
This browser could not save your progress. Changes last until you leave the page.