Q. Is there anything wrong with the following class design? If yes, can the design be improved?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.ocp; import javax.management.RuntimeErrorException; import org.apache.commons.lang.StringUtils; public class MathOperation { public int operate(int input1, int input2, String operator){ if(StringUtils.isEmpty(operator)){ throw new IllegalArgumentException("Invalid operator: " + operator); } if(operator.equalsIgnoreCase("+")){ return input1 + input2; } else if(operator.equalsIgnoreCase("*")){ return input1 * input2; } else { throw new RuntimeException("unsupported operator: " + operator); } } } |
JUnit test class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.ocp; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class MathOperationTest { MathOperation operation; @Before public void init(){ operation = new MathOperation(); } @Test public void testAddition() { Assert.assertEquals(8, operation.operate(5, 3, "+")); } @Test public void testMultiplication() { Assert.assertEquals(15, operation.operate(5, 3, "*")); } } |
A. It’s not a good idea to try to anticipate changes in requirements ahead of time, but you…