1

I have written a piece of lousy code in C#.NET and i want to optimize it.

All i can think of at the moment is to separate the common portions into a separate method.

Code :

if(condition1)
{     
   switch(condition)
       case 'A' :   //Some code
        break;
       case 'B' :   //Some code
        break;
       case 'C' :   //Some code
        break;
}

else if(condition2)
{     
   switch(condition)
       case 'a' :   //Some code
        break;
       case 'B' :   //Some code
        break;
       case 'C' :   //Some code
        break;
}

Note that the case statements conditions for case 'B' and case 'C' are common.

Any help on improving the code is deeply appreciated.

3
  • 2
    Maybe merge the switch statements and put the if/else inside the branches where applicable? Commented Aug 1, 2012 at 8:47
  • 2
    Can you provide more context? You may be able to completely remove the switch statement based on the context. Commented Aug 1, 2012 at 8:54
  • 1
    Moving common code in a little private helper method is entirely acceptable and common to make code DRY. The jitter will move it back again, if it can, by inlining it so you don't lose the speed. Commented Aug 1, 2012 at 9:00

4 Answers 4

2

Why don't you stack the case statements if their code block should do same code

Like this

case 'B' :
case 'C' :
{
//Do Some Code
}
break;
Sign up to request clarification or add additional context in comments.

Comments

1
case "a":
case "A":
    if ( condition1) {
        ...
    }
    else if { condition2}
        ...
    }
    break;

Comments

1

All you can do is putting the common code together and check the additional condition there.

switch(condition)
{
   case 'A':
     if(condition1) //do something
     else //do something
     break;

  case 'a':
   same as above

  case 'B':
    break;

  case 'C':
    break;
}

Comments

1

I think even if you optimize that piece of code, it would still be very fragile and hard to maintain. I would suggest to try to refactor it using strategy-pattern for example (if it's possible of course).

You would benefit a lot, cause you isolate each routine and do it OOP-way, making it easier to change and maintain in future.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.