Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring multiple switch statements with a more Elegant code

Tags:

.net

c#-2.0

In my application, i have to perform many tasks based on a variable value(m_iIndex) in many of my methods. For achieving it i use switch case statements in most of my methods

For ex :

MathMethod()
{
   switch(m_iIndex)
   {
    case 0 : CallAddition(); break; 
    case 1 : CallSubtraction(); break;
    case 2 : CallMultiplication(); break;
    case 3 : CallDivision(); break;
   }
}


StrangeMethod()
{
   switch(m_iIndex)
   {
    case 0 : CallStrange(10,"John"); break; 
    case 1 : CallStrange(20,"Paul"); break;
    case 2 : CallStrange(30,"Kurt"); break;
    case 3 : CallStrange(40,"Mark"); break;
   }
}

This continues for some 10 more methods. I was wondering is there a way to make this code more elegant and short, by reducing the switch case statements in all my methods.

like image 968
this-Me Avatar asked Jan 22 '26 03:01

this-Me


1 Answers

Lets assume your methods MathMethod() and StrangeMethod() as well as the member m_iIndex are part of a class YourClass. Try to eliminate m_iIndex; instead, use sub classes of YourClass where MathMethod and StrangeMethod are virtual and get overriden in your subclasses.

Here you will find a more elaborate answer.

like image 124
Doc Brown Avatar answered Jan 24 '26 16:01

Doc Brown