What Else?

As software developers, one tool at our disposal, in almost any language, is a switch expression. It comes in many forms: switch, case, when… They are all fundamentally the same. Given a value of an enumerated type, it defines the code behavior for each such possible value.

In Clean Code, Uncle Bob suggests we make sure to only switch over a value once. The idea is once you’ve determined the value, you can convert it to a class with the required behavior. From that point onwards, you can use that class, and not care why it behaves the way it does.

This advice is especially valuable when you need to add another possible value to your enumerated type (or change one of the existing ones). If you haven’t followed the above advice, you’ll end up changing a lot of switch statements. For each one, you’d have to figure out the new expected behavior.

What’s worse, you may not remember all places you need to update. This is because, even though a lot of languages give us some compile-time safety for switch statements, they also allow us to cover all cases we (currently) don’t care about using an else. With an else in place, the code is still valid after adding new values.

This is a problem, because we may want to handle those values differently. With the else in place, we get no warning. It’s amazingly easy to introduce new bugs this way.

So, long story short: if you’re using a switch expression, try to only do it once. Regardless of how many times you end up switching over your values, avoid else. Specify each value explicitly. If you’re lucky enough to have support in your language for grouping values, you can use that to tidy things up.

But no else. Or else…

I may get commissions for purchases made through links in this post.

Published by eranboudjnah

A software consultant and tech lead. Passionate about optimizing as many aspects of my life as possible, to free time for what really matters.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: