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.

  • 2
    Why not give a code sample? – FrustratedWithFormsDesigner Nov 11 '14 at 16:17
  • It sounds like you're using dispatch tables. They are often less efficient than a switch construct, but have the advantage of being modifiable at runtime. Any key-value data type can be used for dispatch tables, such as arrays or hash tables. VTables (a widespread mechanism to implement method dispatch on objects) essentially are a dispatch table created by the compiler. – amon Nov 11 '14 at 16:31

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.

  • +1, especially for OO languages. Smalltalk is existence proof of the fact that you don't need any conditionals at all when you have message dispatch. – Jörg W Mittag Nov 11 '14 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.