samedi 3 octobre 2020

Best way to read commands from a string and execute their respective functions in C#?

The language is pretty much irrelevant here but I was wondering what was the best way of doing this.

Let's say I have a file with all the commands of a dog like this:

bark 10
sit
sit
lay side 17
bark 100
jump

And we have their respective functions programmed in C# or whatever language.

What's the best way to go through this list of strings and run their respective functions?

The most obvious solution to this would be to just do an if else chain or a switch statement. Is there a better way for this?

switch (command)
{
    case "bark":
        (...) parse remaining args
        Bark(arg);
        break;
    case "lay":
        (...) parse remaining args
        Lay(arg1, arg2);
        break;
    ...
    default:
        Console.WriteLine("error");
        break;
}

I feel this is a little hacky. Is there an alternative or some kind of design pattern that fixes this issue in a clean way?

Aucun commentaire:

Enregistrer un commentaire