# Casting the left and right numbers as integers or doubles

How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it.

public Object example(Object left, Object right) {
if(left instanceof Integer && right instanceof Integer) {
switch (operator) {
return (Integer)left + (Integer)right;
case SUB:
return (Integer)left - (Integer)right;
case MUL:
return (Integer)left * (Integer)right;
case DIV:
return (Integer)left / (Integer)right;
}
} else if(left instanceof Double && right instanceof Double) {
switch (operator) {
return (Double)left + (Double)right;
case SUB:
return (Double)left - (Double)right;
case MUL:
return (Double)left * (Double)right;
case DIV:
return (Double)left / (Double)right;
}
} else {
throw new Error("wrong types of arguments");
}
}

• Please provide the context for this code. Where do the inputs come from? What function is this, and what is its return type? – 200_success Aug 12 '18 at 4:33
• The return type is Object and the inputs are Object too which maybe an Int or Double or something else. It throws an error incase it is not an int or double – WAQT Aug 12 '18 at 11:55
• Could you edit the question to include the entire function? – 200_success Aug 12 '18 at 11:58
• Is example really the name of your function? If so, it's a terrible name. – Mast Aug 12 '18 at 12:55
• @Mast it is just an example lol – WAQT Aug 12 '18 at 22:40

One option would be to do your math operations on a double. You can use a generic method that accepts any derivative of the Number class and use the doubleValue() method for your calculation. The caller of the method can cast to Integer as needed:

enum Operators {
SUB,
MUL,
DIV
}

public static <T1 extends Number> Double doMath(T1 left, T1 right, Operators operator) {
switch (operator) {
return left.doubleValue() + right.doubleValue();
case SUB:
return left.doubleValue() - right.doubleValue();
case MUL:
return left.doubleValue() * right.doubleValue();
case DIV:
return left.doubleValue() / right.doubleValue();
default:
return 0.0;
}
}

• Could this be simplified even further? As in, could the list of operators be derived from the switch to reduce data duplication? Is there a reason you're no longer throwing an error if an unsupported operation is passed? – Mast Aug 13 '18 at 5:05
• What's duplicated? Throwing the error was added after I posted my code. And the error is for arguments they're passing not the operation – tinstaafl Aug 13 '18 at 10:08