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

后端 未结 11 1419
悲&欢浪女
悲&欢浪女 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 14:50

    It depends what the switch statement is doing.

    If it's matching characters or strings, say in a parser, and you don't have the same set of patterns repeated everywhere in the code, then a switch statement might be ok.

    If it's matching (say) an integer against a list of allowed values, you can create a base class and a set of derived classes for each value. Then, whatever generates the integer data in the first place can create an instance of the derived class with all of the switch statement "answers" instead.

    A third option is to create a data structure that maps patterns to actions (i.e., functions or objects with virtual methods). You can look up the switch value in this data strucutre, and execute the appropriate action.

提交回复
热议问题