如何重构这个巨大的 switch 语句? [英] How to refactor this huge switch statement?

查看:63
本文介绍了如何重构这个巨大的 switch 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一些代码,其中包含一个 500 行的 switch 语句.基本上,它开启一个string任务并执行相应的动作.

I've inherited some code and within it is a 500 line switch statement. Basically, it switches on a string task and executes the corresponding actions.

从那以后,我将每个 case 语句移到了新类中它们自己的方法中.巨大的 switch 语句仍然存在,但不是内联每个案例的逻辑,而是调用一个方法,所以它更整洁.

I have since moved each case statement in to their own method in a new class. The giant switch statement still exists but instead of inlining the logic each case just calls a method so it's much neater.

问题是这些方法修改了很多不同的东西.50% 的方法需要传入 0 个参数.大约 40% 需要 5 个参数,剩下的 10% 每个需要 10 个参数.

The problem is that the methods modify a lot of different things. 50% of the methods require 0 arguments passed in. Some 40% require 5 arguments and the remaining 10% require 10 arguments each.

目前这个工作,但我想让它变得更好.要么去掉 switch 语句,要么以某种方式减少传入参数的数量.

Currently this works but I'd like to make it better. Either get rid of the switch statement or lower the amount of passed in parameters somehow.

我正在考虑使用将 strings 映射到 Actions 的 Dictionary 来消除整个开关,但这不起作用因为我使用了很多 ref 参数(原始类型)并且没有办法将它们传递给构造函数并让它们稍后被引用修改.

I was thinking of using a Dictionary that mapped strings to Actions to eliminate the entire switch, but this wouldn't work because I'm using a lot of ref parameters (primitive types) and there'd be no way to pass those in to the constructor and have them later be referentially modified.

该问题的明显解决方案是将所有 16 个左右的变量放入一个单独的类中并传递它,但其中很多不是很相关,所以它只是用另一个问题替换一个问题(长参数列表与非-内聚数据类).

The obvious solution to that problem is just to place all 16 or so variables in to a separate class and pass that but a lot of them aren't very related so it just replaces one problem with another (long parameter list with non-cohesive data class).

想知道是否还有其他方法可以改进此代码.感谢阅读.

Was wondering if there were any other ways to improve this code. Thanks for reading.

推荐答案

由于您的问题不包含代码,因此答案也不可能.我认为最好的办法是向您指出有史以来最好的软件书籍之一的第 82 页:重构:改进现有代码的设计.

Since your question includes no code, the answer can't really either. I think the best thing to do is to point you to page 82 of one of the all-time best software books: Refactoring: Improving the Design of Existing Code.

面向对象代码最明显的症状之一是它相对缺乏 switch 语句.大多数时候你看到 switch 语句你应该考虑多态性."

"One of the most obvious symptoms of object-oriented code is its comparative lack of switch statements. Most times you see a switch statement you should consider polymorphism."

然后他列出了一些用于帮助实现这一目标的特定模式.

He then lists some of the specific patterns to be used to help make this happen.

这篇关于如何重构这个巨大的 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆