简体   繁体   中英

How to minimize this switch?

switch(number){
case 2:
    a+=b;
    break;
case 3:
    a+=b;
    break;
case 4:
    a+=b;
    d=f;
    break;
case 5:
    d=e;
    break;
}

how to minimize first three switch cases which which does similar work?

if (2 <= number && number <= 4) {
  a += b;
}
if (number == 4) {
  d = f;
} else if (number == 5) {
  d = e;
}

If you using C# 7, you can make use of Pattern Matching, even though this is an overkill as rightly pointed by Jon Skeet. But in case, you want to stick to switch case, and want to reduce 'case', you could do the following

 switch(number)
   {
    case var _ when number == 2 || number==3 || number==4:
        a+=b;
        if(number ==4)
        d=f
     break;
    case 5:
        d=e;
        break;
    }

You can also replace the first case with variants like

case var _ when new[]{2,3,4}.Contains(number):

Or

case var _ when number >= 2 || number <= 3: // As pointed by earlier answer

Without pattern matching, you could do the following as well

switch(number)
{
case 2:
case 3:
case 4:
    a+=b;
    if(number ==4)
        d=f;
    break;
case 5:
    d = e;
    break;
}

Btw, if your problem is "a+b" is about 60 lines of code, you always have the option to make it a function (and move it out of switch case) to increase its readability.

switch(number)
{
case 2:
case 3:
case 4:
    MethodAbAction();
    if(number ==4)
        MethodDFAction();
    break;
case 5:
    MethodDEAction();
    break;
}

btw, a 60 line method is never fun to read. It would be better if you can split up.

if (number != 5)
{
    a += b;
}

if (number == 4)
{
    d = f;
}
else
if (number == 5)
{
    d = e;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM