- I have a class that receives
keyandvalueparameters from other classes. - Both
keyandvaluearestd::string. - Right now the function
setParameteruses a chained if-else if -else if - else logic:
void setParamater(std::string key, std::string value){
if(key == KEYPARAM_1)
{
//Do something
}
else if(key == KEYPARAM_2)
{
//Do something
}
else if (key == KEYPARAM_3)
{
//Do something
}
else if (key == KEYPARAM_4)
{
//Do something
}
else if (key == KEYPARAM_5)
{
//Do something
}
else if (key == KEYPARAM_6) {
//Do something
}
else
{
//Do something
}
}
-
I find this very ugly and its a code that makes many unnecasary comparisons (the more parameters the more comparions).
-
I had the idea of doing a
mapof string and functinos:std::map<std::string; std::funtion<std::string>>to replace this code. -
The first
std::stringwould be the key, thestd::functionwould replace the code in the//Do somethinglines and the otherstd::stringwould be the value. -
The negative part of this solution is that I would be creating an object for each
keyand I would have to find a nice place to declare all the functions. The good thing is that is easy to call and wont do all the ifelse comparisons. Somehing like this would be kind of pretty:
void setParamater(std::string key, std::string value){
my_map(key, f(value)); //I'm not sure about the syntax in there
}
- Does someone have a better idea to replace the if-else chain? Is the
mapa good idea?
-FYI: each case does something quite different is not just a setters.
Thank you!
Aucun commentaire:
Enregistrer un commentaire