0

[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 breaks 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?

  • What does this question have to do with C#? You're only triggering C# devs with this. Removed tag. – V0ldek Jul 12 '19 at 08:15
  • Because I need solutions for both java and C#, since I have similar situations in code in both languages. – Tanmay Band Jul 12 '19 at 08:17
  • If there's some language-specific opinions regrading these two, I'd like to know. :) – Tanmay Band Jul 12 '19 at 08:18
  • If it is physically impossible for the number of cases to increase, then I'd go for the switch. Otherwise, I'd use a `HashMap` or `Dictionary` depending on the language. – Sweeper Jul 12 '19 at 08:32
  • The number of cases can increase. Are there any performance gotchas for using a dictionary implementation? One answer (and a number of people) in the second link are bent on using a switch. – Tanmay Band Jul 12 '19 at 08:37
  • My taste would be for `switch`, it seems to me that this is exactly what it is for (unless you need to specify the cases in a configuration, for example). – Ole V.V. Jul 12 '19 at 08:52
  • Don’t worry about performance until you absolutely have to. Readable and maintainable code is so much more valuable. – Ole V.V. Jul 12 '19 at 09:11

1 Answers1

0

Below code can give some helping hand for you its written purely in c#

 public class InstanceCreator
{
    /// <summary>
    /// Get the Instance from a fully qualified Name
    /// </summary>
    /// <param name="strFullyQualifiedName"></param>
    /// <returns></returns>
    public object GetInstance(string strFullyQualifiedName)
    {
        Type t = Type.GetType(strFullyQualifiedName);
        return Activator.CreateInstance(t);
    }

    /// <summary>
    /// Invoking the Method By Passing the Instance as well as the Method Name
    /// </summary>
    /// <param name="Instance">Instance Object</param>
    /// <param name="MethodName">Method Name</param>
    /// <returns></returns>
    public object InvokeMethod(object Instance, String MethodName) {
        Type t = Instance.GetType();
        MethodInfo method = t.GetMethod(MethodName);
        return method.Invoke(Instance, null);
    }

}

public class SampleClass {

    public bool doAction() {
        return true;
    }

}

public class TestClass {

    public Dictionary<String, String> FunctionList = new Dictionary<string, string>();

    public TestClass() {

        this.Verify();
    }

    public void Verify() {
        String fullyQualifiedName = typeof(SampleClass).AssemblyQualifiedName;
        FunctionList.Add("SAMPLE", $"{fullyQualifiedName}#doAction");
        InstanceCreator Creator = new InstanceCreator();
        String[] FunctionMapping = FunctionList["SAMPLE"].Split('#');
        object Test = Creator.GetInstance(FunctionMapping[0]);
        bool Result = (bool)Creator.InvokeMethod(Test, FunctionMapping[1]);
    }

}