Bird
Raised Fist0
LLDsystem_design~10 mins

Order state machine in LLD - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define the initial state of the order.

LLD
class OrderStateMachine:
    def __init__(self):
        self.state = "[1]"
Drag options to blanks, or click blank then click option'
ACancelled
BShipped
CCreated
DDelivered
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing 'Shipped' or 'Delivered' as the initial state.
Using 'Cancelled' as the starting state.
2fill in blank
medium

Complete the code to transition the order from 'Created' to the next state.

LLD
def advance_order(self):
    if self.state == "Created":
        self.state = "[1]"
Drag options to blanks, or click blank then click option'
ADelivered
BShipped
CCancelled
DReturned
Attempts:
3 left
💡 Hint
Common Mistakes
Skipping 'Shipped' and going directly to 'Delivered'.
Using 'Cancelled' as the next state after 'Created'.
3fill in blank
hard

Fix the error in the code that checks if the order can be cancelled only when it is in 'Created' state.

LLD
def cancel_order(self):
    if self.state == "[1]":
        self.state = "Cancelled"
Drag options to blanks, or click blank then click option'
ACreated
BDelivered
CShipped
DReturned
Attempts:
3 left
💡 Hint
Common Mistakes
Allowing cancellation after the order is shipped or delivered.
Using 'Shipped' or 'Delivered' as the cancellable state.
4fill in blank
hard

Fill both blanks to complete the method that returns True if the order is in a final state.

LLD
def is_final_state(self):
    return self.state == "[1]" or self.state == "[2]"
Drag options to blanks, or click blank then click option'
ACancelled
BCreated
CDelivered
DShipped
Attempts:
3 left
💡 Hint
Common Mistakes
Including 'Created' or 'Shipped' as final states.
Missing one of the final states in the check.
5fill in blank
hard

Fill all three blanks to complete the transition method that moves the order from 'Shipped' to 'Delivered' or 'Returned'.

LLD
def update_after_shipping(self, returned):
    if self.state == "[1]":
        if returned:
            self.state = "[2]"
        else:
            self.state = "[3]"
Drag options to blanks, or click blank then click option'
ACreated
BReturned
CDelivered
DShipped
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong initial state before update.
Swapping 'Delivered' and 'Returned' states.

Practice

(1/5)
1.

What is the main purpose of an Order State Machine in a system?

easy
A. To track and control the valid states an order can be in during its lifecycle
B. To store customer payment details securely
C. To calculate the total price of an order
D. To manage user login sessions

Solution

  1. Step 1: Understand the role of state machines

    State machines define allowed states and transitions for an entity, ensuring valid progress.
  2. Step 2: Apply to order lifecycle

    For orders, the state machine controls stages like 'Pending', 'Shipped', 'Delivered', preventing invalid jumps.
  3. Final Answer:

    To track and control the valid states an order can be in during its lifecycle -> Option A
  4. Quick Check:

    Order state machine = control order states [OK]
Hint: State machines control valid order stages only [OK]
Common Mistakes:
  • Confusing state machine with payment processing
  • Thinking it calculates prices
  • Mixing with user session management
2.

Which of the following is the correct way to represent a state transition in an order state machine?

class OrderStateMachine:
    def __init__(self):
        self.state = 'Pending'

    def ship(self):
        # Transition from Pending to Shipped
        ?
easy
A. if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition')
B. self.state == 'Shipped'
C. self.state = 'Pending' if self.state == 'Shipped' else 'Shipped'
D. self.ship = 'Shipped'

Solution

  1. Step 1: Understand valid state change syntax

    Assign new state only if current state allows it; else raise error.
  2. Step 2: Check each option

    if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') correctly assigns 'Shipped' if current is 'Pending', else raises exception.
  3. Final Answer:

    if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') -> Option A
  4. Quick Check:

    Valid transition check = if self.state == 'Pending': self.state = 'Shipped' else: raise Exception('Invalid transition') [OK]
Hint: Assign new state only if current state matches [OK]
Common Mistakes:
  • Using comparison (==) instead of assignment (=)
  • Assigning wrong state based on condition
  • Changing method name instead of state
3.

Given the following code snippet for an order state machine, what will be the output after calling cancel() twice?

class OrderStateMachine:
    def __init__(self):
        self.state = 'Pending'

    def cancel(self):
        if self.state in ['Pending', 'Shipped']:
            self.state = 'Cancelled'
        else:
            print('Cannot cancel from', self.state)

order = OrderStateMachine()
order.cancel()
order.cancel()
print(order.state)
medium
A. Cancelled
B. Pending
C. Cannot cancel from Cancelled\nCancelled
D. Error

Solution

  1. Step 1: Trace first cancel call

    Initial state is 'Pending', so state changes to 'Cancelled'.
  2. Step 2: Trace second cancel call

    State is now 'Cancelled', so print message 'Cannot cancel from Cancelled' and state stays 'Cancelled'.
  3. Final Answer:

    Cannot cancel from Cancelled\nCancelled -> Option C
  4. Quick Check:

    Second cancel prints message, state remains Cancelled [OK]
Hint: Check state before transition; print if invalid [OK]
Common Mistakes:
  • Assuming second cancel changes state again
  • Ignoring printed message
  • Expecting error instead of print
4.

Identify the bug in this order state machine method that allows invalid state transitions:

def deliver(self):
    if self.state == 'Shipped' or 'Out for Delivery':
        self.state = 'Delivered'
    else:
        raise Exception('Invalid transition');
medium
A. The method should use 'and' instead of 'or'
B. The method does not change the state
C. The exception message is missing
D. The condition always evaluates to True due to incorrect or usage

Solution

  1. Step 1: Analyze the condition logic

    The condition uses 'if self.state == 'Shipped' or 'Out for Delivery'', which always evaluates True because non-empty strings are truthy.
  2. Step 2: Correct the condition

    It should be 'if self.state == 'Shipped' or self.state == 'Out for Delivery'' to check both states properly.
  3. Final Answer:

    The condition always evaluates to True due to incorrect or usage -> Option D
  4. Quick Check:

    Incorrect or condition causes always True [OK]
Hint: Check boolean conditions carefully for correct comparisons [OK]
Common Mistakes:
  • Using 'or' with string literals incorrectly
  • Forgetting to compare both sides explicitly
  • Assuming condition works as intended
5.

You are designing an order state machine for an online store. The order states are Pending, Confirmed, Shipped, Delivered, and Cancelled. Which design ensures scalability and prevents invalid transitions?

Choose the best approach:

  1. Use a dictionary mapping each state to allowed next states.
  2. Hardcode all transitions in if-else blocks.
  3. Allow any state to transition to any other state.
  4. Use a single variable without validation.
hard
A. Use a single variable without validation
B. Use a dictionary mapping each state to allowed next states
C. Allow any state to transition to any other state
D. Hardcode all transitions in if-else blocks

Solution

  1. Step 1: Evaluate scalability and validation needs

    Hardcoding transitions is error-prone and hard to maintain; allowing any transition breaks rules.
  2. Step 2: Choose dictionary mapping

    Mapping states to allowed next states centralizes rules, making it easy to update and validate transitions.
  3. Final Answer:

    Use a dictionary mapping each state to allowed next states -> Option B
  4. Quick Check:

    Dictionary mapping = scalable, validated transitions [OK]
Hint: Map states to allowed next states for clean validation [OK]
Common Mistakes:
  • Hardcoding transitions everywhere
  • Skipping validation of transitions
  • Allowing invalid state jumps