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) {
case ADD:
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) {
case ADD:
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");
}
}
Object
and the inputs areObject
too which maybe an Int or Double or something else. It throws an error incase it is not an int or double \$\endgroup\$example
really the name of your function? If so, it's a terrible name. \$\endgroup\$