Refactoring multiple statements with more elegant code

In my application, I have to perform many tasks based on the value of the variable ( m_iIndex ) in many of my methods. To achieve this, I use case 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 10 other methods. I was wondering if there is a way to make this code more elegant and shorter by reducing the case switch statements in all of my methods.

+3
source share
2 answers

Try using polymorphism and create a class for each operation. This is called a Command pattern .

, m_iIndex, , :

abstract class Operation
{
    abstract void Execute();
}

class Addition : Operation
{
    public override void Execute()
    {
      // ...
    }
}

// same for Subtraction etc.

void OnAdditionButtonClicked(...)
{
    // Instead of setting m_iIndex to 0, use this instead:
    _operation = new Addition();
}

, , .

+2

, MathMethod() StrangeMethod(), m_iIndex YourClass. m_iIndex; YourClass, MathMethod StrangeMethod .

.

+2

All Articles