17
Why developers should be force-fed state machines - Shopify
shopify.engineeringThis post is meant to create more awareness about state machines in the web application developer crowd. If you don’t know what state machines are, please read up on them first. Wikipedia is a good place to start, as always.
State machines are awesome
The main reason for using state machines is to help the design process. It is much easier to figure out all the possible edge conditions by drawing out the state machine on paper. This will make sure that your application will have less bugs and less undefined behavior. Also, it clearly defines which parts of the internal state of your object are exposed as external API.
Moreover, state machines have decades of math and CS research behind them about analyzing them, simplifying them, and much more. Once you realize that in management state machines are called business processes, you'll find a wealth of information and tools at your disposal.
Recognizing the state machine pattern
Most web applications contain several examples of state machines, including accounts and subscriptions, invoices, orders, blog posts, and many more. The problem is that you might not necessarily think of them as state machines while designing your application. Therefore, it is good to have some indicators to recognize them early on. The easiest way is to look at your data model:
Adding a state or status field to your model is the most obvious sign of a state machine.
Boolean fields are usually also a good indication, like published, or paid. Also timestamps that can have a NULL value like published_at and paid_at are a usable sign.
Finally, having records that are only valid for a given period in time, like subscriptions with a start and end date.
When you decide that a state machine is the way to go for your problem at hand, there are many tools available to help you implement it. For Ruby on Rails, we have the excellent gem state_machine which should cover virtually all of your state machine needs.
Keeping the transition history
Now that you are using state machines for modelling, the next thing
I just assumed all computer science curricula covered state machines
Mine sure as shit hasn't yet and i'm two and a half years in lmfao
It would, but in my experience, people don't utilize this concept as much as they should when designing programs. I personally find it helpful to create a state machine diagram before starting coding. By doing so, you are forced to to consider potential exceptional scenarios from the outset, rather than focusing solely on the happy path and then having to address exceptions as they arise. Although you don't need to handle these issues immediately, it is crucial that your design incorporates provisions for them at least.
Oh I definitely agree, and I appreciate the share, I was just confused by the title of the article a bit.