0

This is part of the code of a calculator that works on command line. It works fine and the math is correct but it's a little redundant:

switch(Operator)
 {
  case "+": result = num1 + num2;
  printResult();
  break;

  case "-" : result = num1 - num2;
  printResult();
  break;

  case "*":
  result = num1 * num2;
  printResult();
  break;

  case "/":
  result = num1 / num2;
  printResult();
  break;

  case "^":
  result = Math.Pow(num1, num2);
  printResult();
  break;

  case "root":
  result = Math.Pow(num1, (1/num2));
  Console.WriteLine("Root degree " + num2 + " of " + num1 + " is " + result);
  break;

  default:
  Console.WriteLine("Invalid operator.");
  break;

}//END SWITCH       

Is there a way to avoid this redundant code like

result = num1 Operator num2;

or

for char o = Operator
result = num1 Operator num2;

Even just for the + - / * operations ?

marked as duplicate by Robert Harvey, user22815, psr, TZHX, Michael Kohne Jul 8 '16 at 16:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • public static void printResult() { Console.WriteLine("\n" + calculadora.result); } – Newbie404 Jun 26 '16 at 13:45
  • @gnat what do you mean? i'm just a begginer :/ – Newbie404 Jun 26 '16 at 14:05
  • 1
    "you should consider refactoring towards a map based and/or polymorphic solution" (see top answer in duplicate) – gnat Jun 26 '16 at 14:07
  • 2
    A genuine parser w/ visitor pattern would clean it up (and quadruple the LoC) – RubberDuck Jun 26 '16 at 14:10
1

First, remove the duplication by moving PrintResult() below your switch. You call it every time (nearly, you'll need to make it a touch more robust I imagine). Then, change your method to return a result instead. This method calculates and prints. It shouldn't, that break SRP.

Now, you could create a dictionary of functions to be invoked.

var operations = new Dictionary<string, Func<int, int, double>>()
{
    { "+", (a, b) => a + b },
    { "-", (a, b) => a - b },
    //...
}

return operations[Operator](num1, num2);

May not compile, I'm typing on my phone. Exception handling left to OP.

Of course, if you get really froggy, you could go create a calculator parser and really overkill the solution.

  • Probably @charlotte. Good call. – RubberDuck Jun 30 '16 at 15:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.