Manage the State with a State Machine
Learn to get an overview of how state machines work.
We'll cover the following
The state in an Elixir project
Handling the state is an important topic in web development these days. There are evolving ideas and practices in both the front and back-end worlds. It’s time we talk more directly about how to manage the state in an Elixir project.
The
We’ll meet these challenges with a purely functional state machine. We’ll learn to use a data structure and multiple clauses of a single function to make decisions and enforce rules in an application.
Our state machine will help us coordinate events and transitions as well. Most importantly, we’ll keep our code clean by separating state management from business logic.
Our first step will be to think a little about what a state really means.
A quick look at a state
Holding the state is an act of remembering. We’re remembering the data that models our system. We especially care about the transformation of that data resulting from actions taken in the system over time. We remember the data by committing it to memory on the host machine.
We save the state so future actions can be consistent with the past. Let’s say we create a new user profile in an application. If the user wants to change their email address later on, we should still have access to their original profile.
Most web applications present a twist to this story. As we mentioned in Mapping Our Route,
As web developers, we typically get around this by storing the state in a database. Since we’re not using a database, we need another place to store state data over time. In the Islands game, we’ll store it in long-running Elixir processes—specifically, in the GenServer
processes.
In Model Data and Behavior, we developed the data to model the domain for Islands. We also wrote functions to transform that data. This is where we currently stand. We have the data, but it is not yet stated.
In Add OTP for Concurrency and Fault Tolerance, we’ll see how to hold that data and its subsequent transformations in the GenServer
processes. This act of holding data in a process over time will transform the data structures we have into a state.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy