As Spoike pointed out, using polymorphism to choose the right error handling method is an option. This approach basically discards 10 + if blocks for a virtual JVM search, defining a class hierarchy.
But before moving on to a full-blown class hierarchy, consider the enum methods as well. This option works well if what you plan to do in each case is pretty similar.
For example, if you want to return a different error message for each ErrorCode , you can simply do this:
// Note singular name for enum public enum ErrorCode { INVALID_LOGIN(100, "Your login is invalid"), INVALID_PASSWORD(101, "Your password is invalid"), SESSION_EXPIRED(102, "Your session has expired"); private final int code; private final String private ErrorCode(int code, String message){ this.code = code; this.message = message; } public String getMessage() { return message; } }
Then your error handling code will be as follows:
ErrorCode errorCode = getErrorCode(); prompt(errorCode.getMessage());
One of the drawbacks of this approach is that if you want to add additional cases, you will need to change the enumeration itself, while with the class hierarchy you can add new cases without changing the existing code.
oksayt
source share