Lapys
Lapys

Reputation: 87

Switch Statements with Variable Case?

I am trying to figure out a more elegant way to handle user input for a small program I'm working on. Nothing is broken, and I know how I could handle it, but it involves reusing lots of code and what I think are potentially unnecessary separate functions.

I am asking the user for input that alters what can be given for input. So on the first pass, there is just one option. On the second pass, there are 4 options. The next pass could be 4 options or 7 options. Etc.

So if I say:

case ConsoleKey.D1:
    function1();
    break;
case ConsoleKey.D2:
    function2();
    break;

Then by pressing 1, I am always going to call function 1. But I won't always need to have function 1 available as an option. But I also don't want to have the options for the user with gaps in between, them, like:

(1) call func1()
(2) call func2()
(5) call func5()
(8) call func8()

I'd rather have the input in order and assigned a function based on what functions are needed, like:

(1) call func1()
(2) call func4()
(3) call func6()
(4) call func9()

Does this make sense? Any help would be appreciated. Thanks!

Upvotes: 1

Views: 115

Answers (1)

user1334319
user1334319

Reputation:

My 2 cents.

public interface IControlBehavior {
     void Activate(int input);
}

public class FirstPhase : IControlBehavior {
    void Activate(int input) {
       //call function1 with 1, function 2 with 2...
    }
}

public class SecondPhase : IControlBehavior {
    void Activate(int input) {
      //call function1 with 1, function 5 with 2...
    }
}

You could even make sure that the input is correct for each phase. Rule of thumb is that whenever you want to refactor a switch you should think "inheritance"!

Upvotes: 2

Related Questions