How do you organize your business logic with finite-state machines? Here is a brief introduction to the concept applied to e-commerce:
🚦 What is a State Machine?
Imagine an intersection with traffic lights to regulate the passage of cars and pedestrians. The light can be:
– Red 🔴 ⇒ In this state, cars must stop, and pedestrians can cross.
– Yellow 🟡 ⇒ In this state, cars should prepare to stop, and pedestrians should not start crossing.
– Green 🟢 ⇒ In this state, cars can proceed, and pedestrians can't cross.
In a state machine, finite states represent specific conditions and transitions between them must follow a logical sequence. You can't jump directly from 🔴 (stop) to 🟢 (go), or from 🟢 to 🟡 (prepare to stop).
💡 Why Use State Machines?
– Clarity: State machines break down your application into manageable states, making the logic easier to read and understand.
– Reliability: Transitions between states are explicit, which reduces the likelihood of bugs.
– Scalability: Introducing a new feature or state becomes simpler, making your codebase more maintainable.
Actually, finite-state machines are not just for software engineers but a useful framework for thinking about processes and systems.
🛒 A Detailed Example with an E-Commerce Cart
Loading State: When the cart is accessed, it's in a ‘loading' state. Here, an ‘invoke' fetches items 📦 from a service. Upon success, the cart transitions to the ‘idle' state and updates its context (think of it as a mini-store) with the fetched items.
Idle State: Think of ‘idle' as a state of readiness. The cart has finished loading, has its data, and is waiting for the user to initiate events.
– Actions: When an item is added, removed, or its quantity updated, actions are executed to mutate the context 🔄, thanks to events that trigger these actions. (The event ‘REMOVE_ITEM' triggers the action ‘removeItem' that mutates the context.)
– Context: The context stores the cart items and a flag to indicate whether the terms and conditions are accepted ✅.
goToCheckout State: To transition to ‘goToCheckout,' a guard condition checks if the terms are accepted 🚫. If yes, the cart moves to this state to complete the purchase 🛍️.
In the end, we can represent all the logic of our cart within a machine in a single place with a formalized and highly deterministic approach. This minimizes side effects. Also, this is just a glimpse of what an FSM can do, followed by parallel state logic, actor model, parent-to-child communication, and so on.
September 11, 2023 - 4:32 am