[EDIT: The code examples below are language-agnostic, although specific answers regarding java
and C#
are encouraged.]
In my game, there's a situation where the code uses a dynamic parameter value (from somewhere else) to decide which function to call from a number of candidates. Something like:
string theParam = parameterFromSomewhereElse;
if(theParam == "apple")
callingFunctionFor_apple();
else if(theParam == "banana")
callingFunctionFor_banana();
else if(theParam == "cat")
callingFunctionFor_cat();
Obviously, one way to do that is the above mentioned if-else
, or even cleaner, switch-case
, but I want to know if there are even better ways, if theParam
can have, like, fifty values.
Two of my thoughts were:
1) Something like a "dynamic named function calling"?
string theParam = parameterFromSomewhereElse;
callFunction("callingFunctionFor_" + theParam);
/// where callFunction is some language defined utility?
2) Make a dictionary, with values as functions
global_dict = {
"apple": callingFunctionFor_apple(),
"banana": callingFunctionFor_banana(),
"cat": callingFunctionFor_cat()
}
and then, simply,
global_dict[theParam](); // or something similar, ignore the syntax
Looked at these questions:
Comments in both indicate a preference to a normal switch-case
, something like:
string theParam = parameterFromSomewhereElse;
switch theParam:
case "apple":
callingFunctionFor_apple();
break;
case "banana":
callingFunctionFor_banana();
break;
case "cat":
callingFunctionFor_cat();
break;
But, in my opinion, it's only visually a little cleaner than if-else
(if not the same, because of the break
s littering throughout.) I'd thought a global dictionary, one place to store all the function references, would be a preferred solution, but I sense there's something more to the tale.
What do you recommend?