DEV Community

Discussion on: Explain a State Machine Like I'm Five

Collapse
 
vonheikemen profile image
Heiker • Edited

I only know about finite state machines, so I'll do that

Imagine a super cool robot transformer that can change to a few shapes. To change from one shape to the next you use a voice command (how cool is that). It can have a human-like form, it can be an animal, a car, and there is this secret command that makes it take the shape of a bucket. At any given time it can only have one shape, if it's a car, is car; if it's an animal, it is an animal. It can't be half car half animal, that's not a thing. To prevent any sort of weird invalid shapes, the designers made it so that you can only transform from human-like to one of the other forms (car or animal or bucket). And when the robot is an animal or car, it can only change to the human form. What's with the bucket thing? Okay, the reason it's a secret is because when the robot changes to a bucket it can't listen to any command, so you can't make it human again (why? I don't know. I didn't design the toy).

This robot is a finite state machine. At any given time it can only be in one state (the "shape"). It has specific transitions from one state to the other (human -> thing or thing -> human). And this transitions are triggered by events, the voice commands. The bucket thing? Well, if it can't listen to any event is not going to trigger any transitions (it also needs those transitions, even if you could listen to an event, but you have no transitions, you're still stuck). So if it gets to the bucket, that is going to be it's final state.

I bet someone here can make an xstate diagram representation thingy of the robot.

Edit: I almost forgot. I have post about finite state machines, it's mostly me playing around with a javascript library, but I think it could help someone (maybe a very smart 5 years old):

Taking a look at finite state machines