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

后端 未结 11 1449
悲&欢浪女
悲&欢浪女 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 15:10

    In general, I think you should refactor only when you need to, such as when you want to add more features, but the current design isn't up for the task. You should then refactor without adding the new functionality, and only then add the new feature.

    In other circumstances, don't bother with refactoring. Do it when you need to, otherwise there are probably more important things to do.

    If you really really need to, then the Visitor Design Pattern is a common switch-case replacement, though you should note it does have drawbacks. (i.e., check out www.objectmentor.com/resources/articles/acv.pdf)

提交回复
热议问题