C# Tip – Convert long if-else and switch statements to a dictionary map

This week, I was working on a program for my client, and want to show you a technique I used to make a function in it smaller and cleaner.

This function gets a value from one part of the program, and determines the equivalent value for another part of the program. The existing code used a switch statement; however, there were about 50 values to convert. This made the function longer than I like.

So, I decided to clean up the function.

This is called “refactoring“. When you refactor code, you don’t change what it does, only how it does it. The purpose of refactoring is only to make the code easier to read and work with.

Here’s what the original code looked like (not my client’s actual code, but a made-up example).

 

Here’s how I changed the function.

 

 

In the changed version, we set up a dictionary with the values. The first parameter in the Add function is the “key”, and the second is the “value”. With a Dictionary, the key values must be unique.

When we define the dictionary, we also state what type of data we want to hold in the key and value. In this case, our key is a string, and the value is an integer.

If we ever need to add new codes, or change existing ones – which is very likely for this program – we only need to add or change values in the dictionary.

You can use this technique with long “switch” statements, or with long “if/else-if” statements.

 

Result

This isn’t a big change to the program. It just makes the function a little smaller, and a little easier to read. However, a small change can give you many benefits over time.

The project I’m working on has many phases, planned for several years. In that time, the code will probably be worked on by dozens of programmers. Making the code easier to read will make it easier to change (correctly, since it won’t be long, or confusing).

Refactoring follows the philosophy of “leave it better than you found it”. And it’s frequently a good idea – especially if the program will be used for a long time, if it is likely to need changes in the future, the refactoring is easy to do, and the change has a low risk of breaking the program.

Leave a Reply

Your email address will not be published. Required fields are marked *