CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 3 of 6 · 2 min read

States and classes

A state table first, then the classes.

When the same button means different things at different times, draw a table of states and events. Here there are two states.

State insert coin select cancel
Idle (no money) Take the coin, go to HasMoney Say "insert coins first" Say "nothing to return"
HasMoney Take the coin, stay Check stock, balance and change. On success dispense and go to Idle Return the inserted coins and go to Idle

Without the state pattern, each method would start with if (balance == 0) ... else ..., and a third state (such as out of service) would add a branch to every method. With the pattern, each state is a class with the three methods, and a new state is a new class (Level 4, module 3).

Class Kind Job in one sentence
VendingMachine context Holds the current state and the balance, and passes each user action to the state
State interface insert, select, cancel
Idle, HasMoney classes What each action does in that state
Inventory entity Holds products and stock counts, and refuses to take from an empty slot
CoinBank entity Holds the count of each coin and makes change
Product value Name and price

Who owns which rule:

  • Stock rules ("cannot take from an empty slot") belong to Inventory.
  • Coin rules ("these coins add up to this amount") belong to CoinBank.
  • The order of checks on a sale belongs to the HasMoney state, since it only makes sense there.
VendingMachine  has-one  State (current)
VendingMachine  has-one  Inventory
VendingMachine  has-one  CoinBank
Idle, HasMoney  implement State

State (of a machine)

A state is a named condition of the machine that decides what each user action does.

Example: Idle, where selecting a product only asks for coins.

Check yourself: 1. Which state allows a sale? 2. What would a new "out of service" state need? 3. Which class knows how to make change?