alternatives to switch-case
Solution 1
You can use a Dictionary<int,Func<bool>>
, with this you will have less cyclomatic complexity, see the example:
Note: i use Dictionary to show that you can use any type as key, for example a
string
with a name, or anenum
.
Dictionary<int,Func<bool>> proc = new Dictionary<int,Func<bool>>
{
{0, proc0},
{1, proc1},
{2, proc2},
{3, proc3},
}
and than use like that:
while (true)
{
if (sig_IsExit())
break;
Thread.Sleep(500);
bRetSts = false;
bRetSts = proc[StepCurrent]();
if( bRetSts )
StepCurrent++;
}
Solution 2
bRetSts = (StepCurrent == 0)? proc0():
(StepCurrent == 1)? proc1():
(StepCurrent == 2)? proc2():
(StepCurrent == 3)? proc3():
false; // it could be more proper to throw an exception
or, perhaps more appropriate if all procX
have the same signature:
var funcs = new Func<bool>[] { proc0, proc1, proc2, proc3 };
funcs[StepCurrent]();
Chengting
Updated on June 04, 2022Comments
-
Chengting almost 2 years
I want to know if this kind of switch-case usage is appropriate, or there is any other alternatives (patterns)?
the following is part of my program:
the basics is I am doing a sequence of actions
generally program control is following the sequence of case one by one;
usually any specific case is not finished in its first call, we have to wait until the procX
return
strue
. (waiting for instrument response or action completion);jump to a specific
case
is possible (changingStepCurrent
in the sampling code).
I found this kind of
switch
-case
is hard to maintain, especially by changing theStepCurrent
to direct control flow. And code looks ugly.is there any better method?
note: though I am using C#, the problem might not be limited to it.
while (true) { if (sig_IsExit()) { break; } Thread.Sleep(500); bRetSts = false; switch (StepCurrent) // nSeq) { case 0: bRetSts = proc0(); break; case 1: bRetSts = proc1(); break; case 2: bRetSts = proc2(); break; case 3: bRetSts = proc3(); break; case 4: ... } if( bRetSts ) StepCurrent++; }