Often times we see stuff like that in code:
void myFunction(string someValue) {
if (someValue == "a") {
// ...
} else if (someValue == "b") {
// ...
} else if (someValue == "c") {
// ...
} else {
// ...
}
}
This is a basic example of mapping data to actions. Doing this using a big switch
or a long series of if else-if
is considered a bad practice.
A common approach is to use a Dictionary
(or HashMap
, etc.) as a replacement. E.g.:
Dictionary<string, Action> _actions = new Dictionary<string, Action>();
// .. fill in the dictionary somewhere
void myFunction(string someValue) {
_actions[someValue]();
}
Somehow it does feel like a more elegant approach. However I don't see how it is so.
When mapping data to actions, how is a dictionary better than a big/growing switch
?