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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With