Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: ATM State and Sequence Model

Model an ATM: a hierarchical state machine with PIN retries and timeouts, sequence diagrams for withdrawal, a contract for withdraw, and a running simulation.

The ATM is a classic modeling exercise because it is rich in behavior: states, retries, timeouts, interactions with a remote bank, hardware devices and strict rules about money. In this project you build a state machine with hierarchy and guards, a sequence diagram for the main scenario, contracts for the operations, and a simulator that executes the state machine. Together they show how behavior diagrams, constraints and code reinforce each other.

The brief

A customer inserts a card. The ATM asks for a PIN. After three wrong PINs, the card is kept. With a correct PIN, the customer can check the balance or withdraw cash. A withdrawal is approved only if the bank confirms the balance, the amount is a multiple of 10 and the ATM has enough cash. If the customer does nothing for 30 seconds, the card is returned. The customer can cancel at any time before the cash is dispensed.

Step 1: the state machine

A flat machine would repeat the "cancel" and "timeout" arrows on every state. A composite state Session captures them once.

stateDiagram-v2
    [*] --> Idle
    Idle --> Session : cardInserted
    state Session {
        [*] --> AwaitPin
        AwaitPin --> AwaitPin : wrongPin [tries < 3]
        AwaitPin --> Menu : correctPin
        Menu --> Withdrawing : chooseWithdraw
        Menu --> ShowBalance : chooseBalance
        ShowBalance --> Menu : ok
        Withdrawing --> Menu : declined
    }
    Session --> Dispensing : approved
    Session --> CardKept : wrongPin [tries = 3]
    Session --> Idle : cancel / returnCard
    Session --> Idle : after(30 s) / returnCard
    Dispensing --> Idle : cashTaken / returnCard
    CardKept --> Idle : staffReset

Mermaid cannot draw arrows that leave a substate, so approved and the third wrongPin are drawn from the Session boundary; in a UML tool they start at Withdrawing and AwaitPin.

Points to review:

  • Entry and exit actions. Session has entry startTimer and exit stopTimer, so the timeout logic is written once.
  • Guards on wrongPin are exclusive (tries < 3 and tries = 3) and complete.
  • Cancel after dispensing is not allowed: Dispensing is outside Session, so cancel is ignored there, which matches the brief (cancel is only possible before cash is dispensed).
  • A real machine would also have a Maintenance state and an OutOfCash state. Add them as an exercise.

Step 2: sequence diagram for a withdrawal

sequenceDiagram
    actor C as Customer
    participant A as ATM
    participant B as BankService
    participant D as CashDispenser
    C->>A: chooseWithdraw(amount)
    A->>A: checkMultipleOf10 and cashAvailable
    A->>B: authorize(card, amount)
    alt approved
        B-->>A: approved(newBalance)
        A->>D: dispense(amount)
        D-->>A: done
        A-->>C: cash, receipt
    else declined
        B-->>A: declined(reason)
        A-->>C: message
    else bank unreachable
        B--xA: timeout
        A-->>C: try again later
    end

The third branch (bank unreachable) is where models earn their keep: the brief did not mention it, but any real ATM must handle it. A good rule: for every message to an external system, ask what if no answer comes?

Step 3: contracts for the operations

TEXT
context ATM::withdraw(amount : Integer)
pre  validAmount:  amount > 0 and amount mod 10 = 0
pre  cashInside:   self.cashRemaining >= amount
pre  inSession:    self.state = State::Menu
post cashReduced:  self.cashRemaining = self.cashRemaining@pre - amount

context BankService::authorize(card : Card, amount : Integer) : Boolean
post consistent:   result implies card.account.balance@pre >= amount

The last postcondition says that an approval implies sufficient funds. It is the key safety rule, and it belongs in a test.

Step 4: simulate the state machine

The simulator below encodes the diagram as a table with guards and timers as events. It runs three scenarios: a correct PIN with withdrawal, three wrong PINs, and a timeout.

Python ATM state machine simulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The log is the trace of the scenario and can be compared with the diagram. The last line shows cancel being ignored in Idle, as intended.

Step 5: test the contract

Turn the withdraw preconditions and the postcondition into checks, including the boundaries.

Python Contract checks for withdraw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extensions

  • Add OutOfService and Maintenance states with an orthogonal region for the cash dispenser hardware.
  • Draw a deployment diagram: ATM, bank gateway, bank mainframe, with network zones.
  • Draw a timing diagram for the 30-second timeout and the 5-second cash-taken window.
  • Add a use case "Deposit cash" and extend the state machine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is Session modeled as a composite state?

    An arrow from the composite boundary applies to every substate inside.
  2. 2. Which guard pair on wrongPin is correct?

    The guards are exclusive and cover all cases.
  3. 3. What question should you ask for every message to an external system?

    Timeouts and failures are the most commonly forgotten branches.
  4. 4. In the model, what happens to a cancel event while in Dispensing?

    Events without a matching transition are discarded.

Summary

  • Composite states remove duplicated cancel and timeout arrows and give entry/exit actions a home.
  • Guards must be exclusive and complete; unmatched events are ignored.
  • Sequence diagrams should include the failure and timeout branches of external calls.
  • OCL contracts record the safety rules; boundary cases become tests.
  • A table-driven simulator lets you replay scenarios against the diagram.

Next: UML Practice Exercises