propose refactoring: Convert switch() to a class hierarchy

Hi.
How about this refactoring: This is a usual case to one-way transform of switch() operator to a class hierarchy - combination of an interface, implementation (one per "case" branch) and a class factory. For instance:

int function calculate(Operation op, int a, int b)
{
swictch (op)
{
case Operation.Plus: return a+b;
case Operation.Minus: return a-b;
}
}

may be converted to:

interface ICalculator
{
int Calculate(int a, int b)
}

class CalculatorPlus : ICalculator {...};
class CalculatorMinus : ICalculator {...};
class CalculatoeFactory {
public static ICalculator Create(Operation op) {..};
}

so the function calculate() will be converted in this way:

int function calculate(Operation op, int a, int b)
{
return CalculatorFactory.Create(op).Calculate(a,b);
}

--
How do you like it?

Please sign in to leave a comment.