Learning how to escape the endless switch/case

Michael Ganchas
2 min readOct 26, 2020
Image from https://www.manypixels.co/gallery/

Hi all!

Today I’d like to share with you how we can make use of polymorphism to prevent multiple (ugly and unmaintainable) switch/case and make our code more SOLID compliant.

When it might be useful

Let’s suppose we have a list of currencies that our program supports, and we’re representing them in a typical fashion: using an enum.

Now, for every currency available, we’ll have certain functionalities associated with it (getting its name, symbol, its value against another currency, etc).

We could be tempted to create a single type, with functions for each functionality and using a switch/case statement in every one of them.

Why avoid it

Even though we cannot (and should not) fully escape from using that approach, we should minimize its use, for at least the following reasons:

  • There’ll be one component who’ll know how to do more than one thing, thus violating the SRP principle.
  • Whenever we add a new enum entry, we’ll need to make sure that every function with those switch/case statements will need to be modified. If you miss one, the program’s behavior might not be the desired one.
  • For each case we add, the bigger each function gets and the less legible and clean it becomes.

The code

We’re going to use C# for this tutorial.

Currencies

First, let’s start by creating our currencies enum:

What a Currency must do

Now, the next to do is to decide what behavior each currency has in our program. For this exercise, we’re going to define the following interface:

Note: The list of available countries for transfers retrieves a List of object for simplicity of this exercise.

What a Currency does

After we’ve defined what they must do, we need to implement it for each currency.

For Euros
For Pounds
For US Dollars

Note: See more about what the sealed keyword and expression body definition (=>) do.

Note 2: I’ve maintained CurrencyApi’s implementation abstract because it’s not relevant to this exercise. Implement it according to your requirements.

The Playmaker

Now, we still need a place for a single redirection component, one that’ll point us to the right component according to what we need. It uses the factory pattern to accomplish that.

Note: We’re using lazy initialization for our program to only allocate memory to the “currencies” dictionary when it is first used. It’s useful to use a dictionary for better performance since it uses indexing to retrieve the correct entry.

Example

A possible implementation to compare the value of the Euro against the US Dollar might be the following:

Note: See more about string interpolation.

That’s it for today. Feel free to ask any questions or add suggestions if you’d like!

Cheers!

--

--