Introducing Turnstile: Finite State Machines in Swift

I guess reaching a certain age makes you reflect on stuff like the meaning of life or the purpose of your work. Not much can be done about the first of those concerns, and if you want to make a somehow decent living, I am afraid you can not do too much about the second either.

However, if you are a Sexy Software Engineer, there is something you can do to fulfil your heart’s desire: open sourcing something.

It does not need to be your life’s work, it does not need to be something that will change the way software is developed, or end world hunger. A repo in github is more than enough.

Finite State Machines

At this point you are probably wondering if this is an actual post about actual software or not. Yes, it is. This is all about State Machines.

State is my favourite design pattern, by far. The first time I heard the words “design pattern” was when I was introduced to State. It was my first day in my first job as an “engineer” (which I later understood was a very different thing as being a “programmer”). To this day, I still remember how I felt when my team lead was explaining it to me: it was a mix of incredulity, fear of the unknown, and a more specific fear of being fired as soon as everyone noticed I was not understanding a single word the team lead was saying.

What problem do State Machines fix?

Indeed.

I guess the easiest way to describe it would be this:

The State Pattern allows objects to behave in different ways depending on their internal state

A simple example of an object that behaves in different ways depending on its internal state might be a play/pause button. If you press the button while it is in the “play” state, whatever is being reproduced will be paused. If you press again, playback will start again.

Now imagine the same button, with another two or three states. Then, the logic to handle the button will start getting more complicated. You might need a switch statement to handle it, you might even need to nest if clauses. In any case, your logic gets quite complicated, and therefore your code will get more error prone and difficult to maintain.

How do State Machines fix that problem?

Instead of having complex logic to handle the different states, declaring a State Machine is just declaring a set of States and the transitions between them.

Transitions are just links between an initial and a final state. Now, it is just a matter of figuring out a way to to trigger those transitions, in order to change the object behaviour.

Turnstile

Turnstile is a lightweight implementation of the State pattern in Swift.