I have enum say ErrorCodes that
public enum ErrorCodes {
INVALID_LOGIN(100),
INVALID_PASSWORD(101),
SESSION_EXPIRED(102) ...;
private int errorCode;
private ErrorCodes(int error){
this.errorCode = error;
} //setter and getter and other codes
}
now I check my exception error codes with this error codes. I don’t want to write if this do this, if this do this. How I can solve this problem (writing 10+ if blocks)
Is there any design patter to that situation ?
Thanks
As pointed out by Spoike, using polymorphism to pick the right error handling method is an option. This approach basically defers the 10+ if blocks to the JVM’s virtual method lookup, by defining a class hierarchy.
But before going for a full-blown class hierarchy, also consider using
enummethods. This option works well if what you plan to do in each case is fairly similar.For example, if you want to return a different error message for each
ErrorCode, you can simply do this:Then your error handling code becomes just:
One drawback of this approach is that if you want to add additional cases, you’ll need to modify the enum itself, whereas with a class hierarchy you can add new cases without modifying existing code.