mardi 2 février 2016

How do I refactor a switch-case using polymorphism?

From the console I get commands in the format [command][position][value] e.g. multiply 2 3 and I am supposed to manipulate an array of integers according to the command. For example if i have int[] arr = new int[] { 0, 2, 0 }; after executing the "multiply 2 3" command the array should look like { 0, 8, 0 }

The way I'm doing it now is by giving the info to a method that performs that manipulation.

static void PerformAction(int[] arr, string action, int position, int value)
    {
        switch (action)
        {
            case "multiply":
                array[position] *= value;
                break;
            case "add":
                array[pos] += value;
                break;
            case "subtract":
                array[pos] -= value;
                break;
        }
    }

My question is - How do I apply polymorphism and/or reflection so I can just say:

ExecuteCommand(int[] arr, string action, int position, int value)

And maybe have a class for each command, so that every command knows how to be executed.





Aucun commentaire:

Enregistrer un commentaire