Here's my scenario:
I have ~100,000 string[]
going into a function called CallCommand(string[] command)
.
I have ~50 static classes, that all contain the same method: public static void ParseCommand(string[] command)
.
My CallCommand
function checks the first parameter of the string[]
and calls the correct class's ParseCommand
.
I'm trying to find a way to call the right function automatically (using generics?) without a switch statement.
Currently, I'm using a large switch statement like so (only showing a few since there are ~50):
public static void CallCommand(string[] command)
{
string commandVerb = command.First().ToLower();
switch (commandVerb)
{
case "add":
AddCommand.ParseCommand(command);
break;
case "attach":
AttachCommand.ParseCommand(command);
break;
case "assign":
AssignCommand.ParseCommand(command);
break;
case "cancel":
RunCommand.ParseCommand(command);
break;
case "center":
CenterCommand.ParseCommand(command);
break;
case "complain":
ComplainCommand.ParseCommand(command);
break;
default:
Log("This command doesn't exist.");
break;
}
}
I wanted to reduce the code a bit, so I tried using a Dictionary<string, Action>
instead (again, reduced the number of key/value pairs here since there's ~50):
private static readonly Dictionary<string, Action<string[]>> handlers = new Dictionary<string, Action<string[]>
{
["add"] = new Action<string[]>(AddCommand.ParseCommand),
["assign"] = new Action<string[]>(AssignCommand.ParseCommand),
["attach"] = new Action<string[]>(AttachCommand.ParseCommand),
["cancel"] = new Action<string[]>(AddCommand.ParseCommand),
["center"] = new Action<string[]>(AddCommand.ParseCommand),
["complain"] = new Action<string[]>(ComplainCommand.ParseCommand)
};
Here's the CallCommand
function after setting up the dictionary:
public static void CallCommand(string[] command)
{
string commandVerb = command.First().ToLower();
handlers[commandVerb].Invoke(command);
}
Finally, here's an example of one of my static classes. They are all set up exactly the same way. They just do different things in their ParseCommand
method:
public static class AssignCommand
{
public static void ParseCommand(string[] command)
{
//do stuff with command
}
}
I understand I would have to refactor my static classes a bit to achieve what I want (if it's possible), I've just been unable to figure out the correct way.