Thank you in advance to read my question.
Is there any way to refactor the code below?
The code below is about handling errors in my project.
I left out if-else codes and changed variable names to make my question simpler. There are more if-else codes and variables in the original.
private static final String NUMBER_ONE = "number.one";
private static final String NUMBER_TWO = "number.two";
private static final String NUMBER_THREE = "number.three";
private static final String NUMBER_FOUR = "number.four";
private static final String NUMBER_FIVE = "number.five";
// ... more error names
public void handler(ApiException exception, String customerNo, String code) {
if (is(NUMBER_ONE, exception)) {
throw new NumberOneException(customerNo, code);
} else if (is(NUMBER_TWO, exception)) {
throw new NumberTwoException(customerNo);
} else if (is(NUMBER_THREE, exception)) {
throw new NumberThreeException(code);
} else if (is(NUMBER_FOUR, exception)) {
throw new NumberFourException(customerNo, exception.toError());
} else if (is(NUMBER_FIVE, exception)) {
throw new NumberFiveException(exception.toError());
// ... too many if-else sentences :-(
}
private boolean is(String errorCode, ApiException exception) {
return StringUtils.equals(errorCode, exception.getCode());
}
I was thinking of either Enum or HashMap, but failed to apply any of them.
The main reason was that each exception requires different parameters each other.
I'm still thinking of using HashMap, but not sure whether it's effective or not.
Take a look at the Factory method pattern, which seems to be the most suited in the case presented.