1

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.

  1. Obviously, my concept is messed up here. Could you guys explain whats going on?

  2. What is better way to get rid of instanceof if-else block?

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • You make a new-abstract super-class which will be extended by all these classes then you can use dynamic binding. – Luai Ghunim Nov 16 '17 at 03:09

0 Answers0