PBP: 078 Value Switches

The idea behind this Best Practice is to explain how a table lookup can be used instead of an if/elsif/elsif/elsif/elsif/else block to make selections from a set of constants.  This is almost always a good choice!

Mr. Conway’s examples are clear and make the point well.  One thing I have seen done is to use a hash; the keys hold the values to check for and the value holds a code block containing what to do.  Indexing hashes is very quick, and the code block then does what is needed.  A set of these definitions and usage is pretty clear, and enormously flexible.

Leave a Reply