I’ve searched for a number of articles on refactoring a large switch statement.
But they don’t do what I want to do. The problem I’m going to to run in to is having a gigantic switch statement which calls a different method depending on two different values, lets say a type and a code.
Currently, I would handle the situation like this:
switch (type)
{
case Types.Type1:
handleType1(code);
break;
case Types.Type2:
handleType2(code);
break;
}
void handleTypeN(code)
{
switch (code)
{
...
}
}
Maybe something which combines the factory and command pattern would help me out? I must be missing something obvious.
How would you refactor this code?
I might need to get a little more specific as to what scenario I’m facing.
I’m receiving packets from a server. A packet contains a type and a code and some specific information.
As soon as data arrives I retrieve the type and the code of the packet and it goes in to the switch statement for the type, after figuring out the type a specific method is called to perform a switch on the code of the packet.
The method that handles the code now decodes the packet further and the process is done.
+----------+ +----------+
| | Packet | |
| Server | -------------> | Client |
| | | |
+----------+ +----------+
|
|
(Switch on the type of the packet and call a specific method)
|
|
(Switch on the code of the packet and call a specific method)
|
|
(Respond to the server or not)
I think it depends what kind of code improvement you’re trying to do.
If you have the luxury of actually making big design changes, then I’d suggest polymorphism:
Create an abstract Packet class.
Create a class for each packet type.
Create a factory method, that receives a raw server packet, and creates the right packet class object.
Each packet class type will have its own implementation of the job it needs to do.
If you don’t have the luxury of doing large design changes (which is often the case):
Keep the switch, each switch case will call a properly named function that will do what it needs to.
Create a matrix, that for each cell [T,C] will hold a reference to a function that will handle a Packet with Type T and Code C.
The matrix should be initiated once (hard-coded, no way around that) at startup of program or class.
This will give you better performance than a long switch block (direct access to code, no logical comparisons)