Bird
0
0

Identify the bug in this order tracking state machine snippet:

medium📝 Analysis Q14 of 15
LLD - Design — Food Delivery System
Identify the bug in this order tracking state machine snippet:
state = 'shipped'
event = 'cancel_order'
if state == 'placed' and event == 'cancel_order':
    state = 'cancelled'
elif state == 'shipped' and event == 'cancel_order':
    print('Cannot cancel after shipping')
else:
    state = 'cancelled'
print(state)
AThe else block cancels order even after shipping
BMissing transition from 'placed' to 'shipped'
CNo print statement for cancellation confirmation
DState variable is not updated correctly for 'placed' state
Step-by-Step Solution
Solution:
  1. Step 1: Analyze conditions for state 'shipped' and event 'cancel_order'

    The if does not match. The elif matches, prints 'Cannot cancel after shipping' but leaves state unchanged. However, if event were different (e.g., 'deliver_order') with state='shipped', if and elif fail, else wrongly sets state='cancelled'.
  2. Step 2: Identify why this is a bug

    The else acts as a catch-all, allowing cancellation of shipped orders for unhandled events, contradicting the intent to prevent cancellation after shipping.
  3. Final Answer:

    The else block cancels order even after shipping -> Option A
  4. Quick Check:

    Else wrongly cancels unhandled shipped cases [OK]
Quick Trick: Else block can override specific conditions--check carefully [OK]
Common Mistakes:
  • Ignoring else block effects
  • Assuming print prevents state change
  • Not testing all branches

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes