A
A
Andrey Tatarnikov2014-03-06 16:31:41
Algorithms
Andrey Tatarnikov, 2014-03-06 16:31:41

How to implement elegant code flow?

I am writing a system for the customer, in the main part of which is the execution of a certain scenario, depending on the parameters.
There are only two parameters (I give a simplified code):

string paramA;
string paramB;

paramA can have 2 values ​​- in, out. paramB - 5 values: one, two, three, four, five.
When each pair of paramA-paramB values ​​occurs, several actions are performed sequentially, and the actions for all pairs are the same, but start in a different order.
All actions are methods of one class. Options are global.
Now the code looks something like this (I didn’t fill in all the branches, and so the essence is clear, I think):
Worker w = new Worker();

switch (paramA)
{
  case "in":
    switch (param2)
    {
      case "one":
        w.do1();
        w.do2();
        w.do3();
        break;
      case "two":
        w.do2();
        w.do4();
        break;
      case "three":
        w.do1();
        w.do5();
        w.do2();
        break;
      case "four":
        break;
      case "five":
        break;
    }
    break;
  case "out":
    break;
  default:
    break;
}

There are only 20 methods. It turns out a terribly huge switch, not to mention the fact that there is a lot of duplicate code in the cases (because the same methods are called).
Please, is there a way to make this easier? For example, to somehow assemble a structure like this:
in-one => { w.do1(); w.do2(); w.do3() }
in-two => { w.do2(); w.do4(); }

And execute the desired block depending on the key?
My experience in c# (two weeks) is not enough to fantasize something.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Keith, 2014-03-06
@crackpot

Create a list of all tasks, and a strategy for execution.

var Actions = new Dictionary<String, Action> {
    {"foo", w.foo },
    {"bar", w.bar }
};

var Strategies = new Dictionary<String, List<String>>(){
    {"in one", new List<String> { "foo", "bar" } }
};


// run
var actions = Strategies["in one"];

actions.ForEach((action)=> Actions[action]());

Of course, you can remove `Actions` and pack methods immediately into a strategy, or use reflection to call methods. Do as you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question