A state machine can hold all possible states of something and the allowed transitions between these states. For example, the state machine for a door

State Machines in Ruby: An Introduction

submited by
Style Pass
2022-06-22 11:30:05

A state machine can hold all possible states of something and the allowed transitions between these states. For example, the state machine for a door would have only two states (open and closed) and only two transitions (opening and closing).

On the other hand, complex state machines can have several different states with hundreds of transitions between them. In fact, if you look around, you will notice finite state machines surrounding you — when you buy from a website, get a pack of crisps from the vending machine, or even just withdraw money from an ATM.

When do we need a state machine in development? The simple answer is whenever you want to model multiple rules for state transitions or perform side-effects on some transitions. The key here is to identify parts of your application that would benefit from a state machine. A good example that always works for me is an Order in the context of an e-commerce application.

Visualizing the order in the form of a state machine immediately allows us to clearly understand the full flow, from ordering the product to delivery. And for us developers, it enables clear, set steps on what can and cannot be done at particular points in that flow.

Leave a Comment