this-Me
this-Me

Reputation: 2145

Refactoring multiple switch statements with a more Elegant code

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.

Upvotes: 3

Views: 508

Answers (2)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174279

Try using Polymorphism and create a class per operation. This is called the Command pattern.

I can only guess on how you set m_iIndex, but the following example demonstrates what I mean:

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();
}

If you provide more context, I can change my example to better meet your requirements.

Upvotes: 2

Doc Brown
Doc Brown

Reputation: 20044

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.

Upvotes: 2

Related Questions