开发者

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 sta开发者_运维技巧tements in all my methods.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜