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?


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 is a lightweight implementation of the State pattern in Swift.

Creating a State Machine can be achieved like this:

Then, it’s good to have some transitions between States. You know, in order to transit between events and stuff:

(Now it might be the perfect time to reflect on how awesome it is that Swift supports emoji)

Triggering transitions is as easy as:

Turnstile is distributed as a CocoaPod, and is available on github. It includes a sample project that illustrates the way to create and use Finite State Machines.

Bash tip: search history

I am lazy. And I am a developer. Some would even say that I am a developer because I am lazy.

Also, my memory is not what it used to be. So, often times, I can not remember the exact syntax of a command I kind of recall typing in the bash shell.

For example, I kind of recall that in order to build and deploy one particular app for QA, I need to run a gradle task with a parameter containing the letters “QA”. But I don’t recall the specific format.

Here comes history to the rescue. A fuzzy search on the history is easy:

Now, I can execute any of those particular results directly by number, just doing:

The Payroll Machine.

Or, as some would say, the story of how some complexity might be necessary sometimes. Or, yet another edition of Looking at the Wrong Abstraction.

The difficult solution

Imagine you need to develop an application that calculates a company’s payroll. Let’s assume that we have three different roles within the company (Developer, Systems Architect, Development Manager, and since this is a modern cool and hip company that does scrum, a Product Owner), and that different roles have different salaries.

The simplest approach

Well, you could argue that it does not actually matter too much, when calculating the payroll, if an employee is a Developer or a Systems Architect. So, one sensible approach might be to model all employees as instances of a class like this:

Now, calculating the payroll is just a matter of doing something like this:

Real life sucks. Or requirements change

I bet you have been there a thousand times. Your app is all app and running, processing data full steam ahead, doing what is expected to do, and doing it well, when suddenly… requirements change.

In this case, the CTO demands a new feature: he should be able to assign multipliers to specific employees, so he can modify their salaries temporarily.

The flexible solution. Or, the mega-awesome although apparently slightly over-engineered solution, that after some consideration, happens to be just awesome and not over-engineered at all

First, I’ll show you all the codez. The I’ll discuss all the codez.

Now, there are different kinds of Employees. To me, that means that each of those “kinds” has to be modelled by a different class. Why? Because they represent different behaviours. As you know, a PO does not do the same things a Developer does.

However, it is true that I am only interested in part of the behaviour of those different kinds of Employees. That is already abstracted by the interface!

Is there repetition? Yes, apparently, but I wouldn’t call it repetition, I would call it specialisation. If there is something else to be taken into account when calculating a salary (for example, manage,went might have part of their salaries payable in shares dividends and whatnot), the specific class that models a PO can implement that specific behaviour.

Also, this solution improves encapsulation. The responsibility of calculating each employee’s salary is well encapsulated, and is completely opaque to the calculatePayroll method.


Often times, a flexible solution requires more code than a simple one. Well, that’s life, I guess: if you want something done properly, you will need to put some serious work into it. It does not matter if it is installing a new fridge in your kitchen, or writing a new method in your code.

But the key here, again, is that being able to identify the right abstractions makes a huge difference in the scalability, modularity and cleanness of your code.

Swift tip: enumerations are first class types

The Book says it without any doubt:

Enumerations in Swift are first-class types in their own right

But wait, there is more! (I love the way my blog’s theme formats quotes, so I

Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration’s current value, and instance methods to provide functionality related to the values the enumeration represents.

But wait, there is even more!

Enumerations can also define initializers to provide an initial member value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.

Yes, if you ever had to write Objective-C for a living, sooner or later you would find yourself in a spot where you would need to loop all the values in an enumeration.

It was not a big deal, because, well, Objective-C enumerations where collections of integers. So all you had to do was end the enumeration with some sort of marker, that indicated you that you were done.

Well, Swift is different. And this time, that’s for the best. Consider an enumeration like this:

Would there be any safe and maintenable way to loop all the values in that enumeration? Indeed, there would be, thanks to Swift’s Sequences and Generators.

Sometimes nothing is something. Or the null object pattern with a touch of the decorator pattern

Or why if clauses should die in a fire.

This post has been lingering, locked up in my drafts folder (which is not an actual folder, but all the cool kids say that, so bear with me on this) for some time.

Yesterday, I stumbled upon this talk by Sandi Metz, because, yes, sometimes I search Youtube looking for recordings of talks about OOD. I am a big fun on Sandi’s talks, and this one did not disappoint me, as usual. And it also gave me the push needed to publish this post

If clauses breed, and sometimes, nothing is something

I am not a big fan of if clauses. I know they are necessary, but I try to avoid them as much as possible, specially when they are type checks.

Type checks are bad

Period. There is always someone that will tell you that type checks might be necessary sometimes, but truth is they are one of the biggest and stinkiest code smells.

“What is a type check?” you might ask. Fair enough; this is a type check:

This is the quintessential example of why type checks are wrong, and you will find a thousand slightly different variations of it on the interwebs.

What’s wrong with that? Simple

Type checks are a sign of bad design

The previous code sample is the perfect example of how a type check is a symptom of a bad abstraction. A Fish and a Spider are both animals, so they both should implement an interface declaring a move() method. Clients of Fishes and Spiders would only be aware of that abstraction and call the move() method. Period.

There is a particularly bad type of the check

And that is the one that does not look like one. It is usually in disguise, pretending to be a null check.

Here is an elaborate example. Consider a Car class:

And a CarWarehouse class:

Now, clients of the CarWarehouse want to checkout cars by name:

The forEach method will crash, because it is trying to call getName on something that is null.

Fine, you might think, I will just filter the stream to remove the objects that are null:

But that’s just bad.

Type checks breed

Once you need to start filtering your results, once a client of a class A needs to start performing a type check on the values returned to it by that class, you are going to need to repeat those checks every single time you want to use that class A.

Why? Because you expect the values returned by A to be of at least two different types: null and whatever it should actually be returning.

So, how what can I avoid those type checks?

Making your classes meet the expectations they set. Simple as that.

Which, of course, happens to be not that simple. But seriously, if clients of your class are expecting a collection of entities that respond to a particular message (note the Smalltalk-speak), make sure that all the entities your class returns respond to that message. Again, simple as that.

In the previous example, what do I want exactly? I want all the objects returned by CarWarehouse to respond to getName. Then all I have to do is return a collection of objects that respond to getName. And if there is no object to return, then I will return something else that still responds to that message.

The Decorator pattern. Sort of.

Here come the big guns! Design patterns to the rescue! Not too long ago, I ranted about how design patterns are abused.

In this particular case, I m going to adapt one of the patterns in the catalog, the Decorator Pattern, to wrap my Car objects:

Notice how SafeCar extends Car. That allows me to do the following:

Which, as you can see, is basically creating a null object, sort of. Again, I am taking the liberty of adapting the pattern to my needs.

And now, clients of my CarWarehouse can conduct their business merrily:


What matters are not the tools you have, but how you use them. Over-abstraction is bad. Over-engineering is bad. Knowing the tools in your belt, knowing how to adapt them and how to let them work together to solve your needs is what matters.

Oh, and sometimes, you need something to help you deal with nothing.

Brew tip: linking to a specific version of a package

Homebrew is awesome.  If you are a developer, and use a Mac in your daily adventures, you should install it. Period.

This little tip might be handy, specially when you want to rollback to a previous version of a package after an update. Because, you know, shit happens, and more often than not, updates break stuff.

You can list all the versions of a package installed in your system:

And to force the system to use a particular version:



Acronyms galore!

If you have read any other post in this blog you might have noticed an emerging pattern: I like simplicity.

Over-engineering much?

I bet you have read the following quote before, in any of its multiple forms

A junior engineer creates complex solutions to complex problems, an more experienced engineer creates simple solutions to simple problems, and a senior engineer creates simple solutions to complex problems.

I would reduce that to something even simpler (see, the same pattern again)

Some engineers create simple solutions, some engineers create complex solution. The complexity of the problem does not actually matter.

In my experience, there is an inflection point in every developer’s career, right at the spot where said developer first encounters design patterns. Suddenly, the whole world becomes a playground, where everything can and will be modelled as a use case of a design pattern.

Don’t get me wrong. There will be plenty of life-changing moments in a developer’s career, but this one affects each and everyone of us at some point or another.

Design patterns

Design patterns are solutions to problems that you will find again and again. Every developer should know their patterns. They provide a shared language, a lexicon, so to speak, that allows developers to describe a problem in a few words. Phrases like “that’s a command” or “use a factory for that” should provide enough information for any developer to know what to do.


As usual, “the virtue of justice consists in moderation”. If is very easy to turn into a pattern-freak, and start seeing patterns everywhere. That syndrome, if left unattended, can lead to a serious disease: over-engineering.

The problem: over-engineering

This is, sadly, an unrecoverable disease. Some symptoms are using interfaces that extend tag interfaces to type method parameters, trying to turn everything around you into a UML diagram, using the term “business domain” more than once in a single week, and generally speaking, writing code that solves problems that you don’t have.

The solution: keeping it simple

Here is where all the fancy acronyms in the post title come into play. KISS (Keep it Single Stupid) and YAGNI (You Ain’t Gonna Need It) are two terms easy to remember and understand. But in a way, both can be reduced to a very simple principle

Occam’s Razor

Occam’s Razor is a problem-solving principle devised by a William Ockham. There are a thousand variations of the principle’s formulation, but I am extremely fond of this one:

Frustra fit per plura quod potest fieri per pauciora (It is futile to do with more things that which can be done with fewer)

In other words: less is more.

Simplicity FTW

There are many benefits in not over-designing or over-abstracting at an early stage.

It is very difficult to see deficiencies in overly complicated code

Well, sometimes the trees don’t let you see the forest and so on and so forth. Complicated code is difficult to read. Too many abstractions make difficult to follow the flow, to understand what is happening.

However, when dealing with simpler code, all the deficiencies will be extremely easy to identify.

Allowing some duplication at early stages simplifies the design

DRY FTW! Sure, but sometimes, a little bit of D is precisely what you need in order to identify what you should abstract and generalise.

You can not foresee the future.

If you could, you would have probably won the lotto by now, and you would live a happy life. However, here you are, reading this.

Adding layers upon layers of abstraction to accommodate future changes in the system is fun, and makes you feel smart, but it is very likely that many of those layer will not be actually necessary.

In a month’s time, you will have to read the code you write today.

Right before extracting that interface that declares just one method that receives something typed as another interface as parameter, ask yourself: “will I still understand what I did here in a month’s time?” If the answer is no, well, you know what not to do.


Life as a software engineer is complicated enough as it is. Adding to many abstractions too early might make things too complicated.

Object Oriented Design is all about trade-offs. Often times, the simplest possible solution is the best one in the long term, even if it is only because it makes your mistakes and bad decisions popup immediately at you.

Keep it simple!

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.

C. A. R. Hoare

Git tip: aliases

The title is a little bit misleading, because this post is going to cover both a Git and a Bash tip. But this is my blog, so I title my posts the way I want.

Please, bring on some tips!

This is a tiny little trick that may be useful only if you ask Git to fulfil your wishes using the command line. Which you should probably be doing at this point, if you want to call yourself a real developer.

Git commands are totally long and totally hard to remember. True. But what if they could be shortened?

Well, in a way, git commands can be shortened. Or at least, adapted to your personal preferences, thanks to aliases.

Aliases can be global or specific to a repository. For example, if you are bored of typing:

You can create a “local” alias:

And from that moment on, you can just do this:

And voilà.

If you want to apply the alias to all your repos:

And voilà again.

My favorite? This one:

Cool, but what about the bash tip?

Yep, I have one of those as well.

bash (the only true Unix shell) allows the creation of shortcuts to certain commands, called alias. For example, if you find yourself typing a thousand times a day the following command:

Wouldn’t it be neat to be able to just type the following?

Well, that’s easy to do in just to steps. First, edit the bash configuration:

Now add the following alias to that file:

Save and exit, and force bash to refresh:

(Note the space between the first dot and the curly-thingy-that-we-use-in-Spanish-on-top-of-the-letter-n-to-make-it-sound-funny)

Now, when you want to checkout a branch, just do:

Ain’t that neat?