I have following piece of code
public OrgSpecificException translate (Throwable t) {
OrgSpecificException e;
if (t instanceof OrgSpecificExceptionTypeA) {
// do some stuff
e = new SubClassAOfOrgSpecificException("message");
} else if (t instanceof OrgSpecificExceptionTypeB) {
// do other stuff
e = new SubClassBOfOrgSpecificException("message");
} else {
e = new OrgSpecificException();
}
return e;
}
I tried to replace this if-else block with following code
public SubClassAOfOrgSpecificException translateObj (OrgSpecificExceptionTypeA e) {
// do some stuff
e = new SubClassAOfOrgSpecificException("message");
}
public SubClassBOfOrgSpecificException translateObj (OrgSpecificExceptionTypeB e) {
// do some stuff
e = new SubClassBOfOrgSpecificException("message");
}
public OrgSpecificException translateObj (Throwable e) {
// do some stuff
e = new OrgSpecificException("message");
}
and then changed the original method translate
like this OrgSpecificException e = translateObj(t)
. What i thought that by calling translateObj
would be called based on what type of object t
is but to my surprise, it only instantiate translateObj (Throwable e)
and not the other ones.
Now here are my questions.
Obviously, my concept is messed up here. Could you guys explain whats going on?
What is better way to get rid of
instanceof
if-else
block?