- I have a class that receives
key
andvalue
parameters from other classes. - Both
key
andvalue
arestd::string
. - Right now the function
setParameter
uses 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
map
of string and functinos:std::map<std::string; std::funtion<std::string>>
to replace this code. -
The first
std::string
would be the key, thestd::function
would replace the code in the//Do something
lines and the otherstd::string
would be the value. -
The negative part of this solution is that I would be creating an object for each
key
and 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
map
a good idea?
-FYI: each case does something quite different is not just a setters.
Thank you!
Aucun commentaire:
Enregistrer un commentaire