What's the best alternative to an out of control switch statement?

后端 未结 11 1468
悲&欢浪女
悲&欢浪女 2021-02-14 14:20

I have inherited a project that has some huge switch statement blocks, with some containing up to 20 cases. What is a good way to rewrite these?

11条回答
  •  無奈伤痛
    2021-02-14 15:15

    Three suggestions (echoing some already given):

    1. Maybe a switch isn't as bad as you think. It can be ugly if the case blocks are large. Shorten them by extracting the logic into methods.

    2. In an OO language, polymorphism might be the answer, as many have pointed out.

    3. In a functional language, like Javascript, write a function that returns the function you need to run for whatever input. That might use a switch statement itself, or it might use a lookup table.

提交回复
热议问题