There is some nasty legacy code.
std::string xxx = GetCommand(); // get "CommandX";
if (xxx == "Command1")
{
return new Command1();
}
else if (xxx == "Command2")
{
return new Command2();
}
...
else if (xxx == "Command100")
{
return new Command100();
}
I want to improve this code structure.
There were too many comparison. So I put them to a map.
for (int i = 0; i < GetCommandCount(); ++i)
{
// key is a command string
// value is a function pointer which creates it's instance
map.insert(command, a function pointer);
}
// then
ICommand* pCommand = map.getInstance(command);
But this way has to make additional function every time if new command comes.
Yes, the functions might be reasonable. But all the functions just be return new CommandNNN(); I guess there is the way to remove the duplication.
How do you think?
Since all the functions are
return new CommandNNN();, you can use a template function:and bind to this function in your map:
This lets you avoid creating a new function for each command. However, there would still be some duplication in the
map.insert-statements. This could be further reduced by using macros, if that’s your cup of tea:or
I suspect that you can even get the preprocessor to do some counting for you, but that’s outside of my domain.
Applying even more macros, as well as some global state, both of which are frowned upon by many, you can get even tighter coupling: