Prefer Dictionary to Switch Statement
Comparing Ways to Get Filenames
Let's look at three ways in C# to get a filename based on a mediaType text.
1. Using switch
This code uses a switch block. It checks mediaType and returns the matching filename.
2. Using many if statements
This code uses many if checks. If mediaType matches, it returns the filename. The last return is used if no if matches.
3. Using a Dictionary (Map)
This code first creates a Dictionary. A dictionary stores pairs of keys and values (like mediaType-> filename). Then, the function looks up the mediaType in the dictionary.
Why the Dictionary is Often Better
All three ways work. But I like the dictionary better. Here's why:
Easy to Read: The dictionary clearly shows all the pairs (
mediaTypeandfilename) together. The code to get the filename is very short and simple. It separates the list from the action.Easy to Change:
Need to add a new media type? Just add one line to the dictionary list. You don't change the
GetFileNameDeclarativemethod.Need to change or remove a type? Just change or remove it from the list.
Changing
switchor manyifstatements means changing the function's logic, which can cause mistakes.
Follows Good Practice (see OPC): The dictionary idea follows a rule called the Open/Closed Principle. This means the main function (
GetFileNameDeclarative) is closed (you don't need to change it). But it's open to work with new types if you add them to the dictionary list.Can Use External Data: The list of types and names in the dictionary could come from a file or database later. This makes the program flexible without changing the
GetFileNameDeclarativefunction.Good Speed: Looking for something in a dictionary is usually very fast (often called O(1) time), even if the list is very long. A long list of
ifchecks gets slower as the list grows (O(N) time). For a small list like this, the speed difference is small, but the dictionary works better for large lists.
See Open Closed Principle (OCP), Imperative vs Functional (Declarative, Expressive) Style of Programming
See Also: