Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have an occasion of code in which I will draw a different set of buttons in a

ID: 645823 • Letter: I

Question

I have an occasion of code in which I will draw a different set of buttons in a screen (depending on the number of the buttons). One thought (and my current implementation) is to use an action array and call a different action

        Action[] array = new Action[9];
        array[0] = one;
        array[1] = two;
        array[2] = three;
        array[3] = four;
        array[4] = five;
        array[5] = six;
        array[6] = seven;
        array[7] = eight;
        array[8] = nine;

        array[buttons.Count - 1]();
So depending on the number of buttons I call the specific drawing method. Another implementation might be using switch case and would look like something this

switch(buttons.count){
case 1: one(); break;
case 2: two(); break;
.
.
.
.
case 9: nine();break;
}
Are there any pros and cons of using versus the other? Are there any efficiency differences?

Explanation / Answer

IMHO the first one is in most cases preferable. First, in C# you can rewrite the initialization much shorter as

Action[] array = new[]{one, two, thre, four, five, six, seven,eight,nine};
But the real advantage comes when you have to change your actions later, for example, by introducing an additional argument. You then have to change only this line

array[buttons.Count - 1](myArgument);
The switch variant instead needs changes in 9 places instead:

switch(buttons.count){
case 1: one(myArgument); break;
case 2: two(myArgument); break;
...
That is because the switch variant does not follow the "Don't Repeat Yourself" (DRY) principle. Imagine what happens when you have not just 9 actions, but 50, or you have to introduce more arguments, or to process a return code from the action / function.

And don't worry too much about performance - in most real-world cases the performance difference is neglectable. And when it is not, you will have to try and measure if a replacement by a switch statement does really bring the necessary performance gain.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote