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

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

问题描述

我继承了一些代码,并且其中包含500行切换语句.基本上,它会打开 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.

我当时在考虑使用 Dictionary string s映射到 Action s来消除整个切换,但这是行不通的因为我使用了很多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天全站免登陆