Curriculum

Curriculum

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.

Selected choicePick a choice below
Result—

Try it yourself

What goes wrong if the system subtracts 1 from availableStock before checking whether the student holds a valid safety badge?

Reveal the explanation
  1. 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

  2. steps in safe order with badge=true, stock=0

    Stopped at stock check; stock remains 0 (never -1); no slip printed

  3. 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

An event waitlist tool registers attendees. Which step MUST run before incrementing registeredCount?
Show the answer and reasoning

Correct answer Checking that registeredCount < capacity

Capacity is a precondition for registration; checking it before incrementing prevents exceeding the room limit.