mardi 3 juillet 2018

Best design pattern to avoid instanceof when working with classes that cannot be modified?

I am overriding a method provided by third-party library class and trying to record exceptions that occur:

@Override
someJavaMethod(arg1, arg2, Exception ex){
        //Declare some variables with default values
    if (ex instanceof SpecificException1)
        //Set values for the variables
    else if (ex instanceof SpecificException2)
        //Set some other values for the variables
    else
        //Do nothing
}

The issue here is that SpecificException1 and SpecificException2 are both third-party exceptions and I cannot modify them.

I understand that using instanceof is not a great way to handle this. What design pattern / OO principles I should use to handle this?

(Also, I was advised to see the visitor and acyclic visitor design pattern, but I am not sure if they can be applied to classes that cannot be modified)

Aucun commentaire:

Enregistrer un commentaire