1

Whenever I feel like choosing from a list of implementations I always prefer to fill a map first and then call whatever I need based on a parameter, instead of using switch or else if statements.

What is the pattern I'm looking for here? I've been told repeatedly that using maps is not the optimal solution for this, but I find writing those statements a bore.

I tagged the languages I'm currently working with, but this is not a language specific question.

enon
  • 161

1 Answers1

4

As amon pointed out in his comment, that's called a dispatch table. It's one way to implement the more general concept of ad hoc polymorphism.

Since nearly every language after C supports ad hoc polymorphism natively in one form or another, it's unlikely that your solution is either more readable or more efficient, except in limited circumstances like deserialization. Even then, more expressive languages have constructs that can help you there, like clojure's multimethods.

Find out how your language does ad hoc polymorphism. It's the right solution for 99% of situations where you need to choose between different implementations.

Karl Bielefeldt
  • 148,830