dimanche 24 septembre 2017

How to elegently call methods by name?

I am implementing a interpreter-like functionality in a project. The goal is to allow the user of this library to call something like Invoke(command, param1, param2, param3...) to invoke different commands. Each command is a method of the class.

My current implementation is like:

class MyTest: IInvokable {
    public void Command1(string pa)
    {
        throw new NotImplementedException();
    }
    public int Command2(string pa, int a)
    {
        throw new NotImplementedException();
    }
    public string Command3()
    {
        throw new NotImplementedException();
    }
    public CommandResult Invoke(string cmd, params object[] p)
    {
        switch(cmd)
        {
            case "Command1":
            case "Command1Alias":
                return new CommandResult(this.Command1(p[0].ToString()));
                break;
            case "Command2":
                *** omitted ***
        }
    }
}

The giant switch-case looks really silly to me. I looked at Command Pattern but don't know if it works here. Any suggestions to make the code better?

Aucun commentaire:

Enregistrer un commentaire