Best design pattern to avoid instanceof when working with classes that cannot be modified?
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.
SpecificException1
SpecificException2
I understand that using instanceof
is not a great way to handle this. What design pattern / OO principles I should use to handle this?
instanceof
2 Answers
2
There are no fundamentally different ways of solving this (at least not in Java). If you were using a language that allows for multi-dispatch, you could overload the message for the different exception types.
I would rather suggest to simply accept it. If at all I would see how the clean code rules help here, for example by making sure that each if block goes into a distinct method.
Well, there is one slightly different approach: you could potentially use a map. Keys would be the exception class, the values would be something that contains the values for your different variables that need to be assigned.
What about throwing the exception in a try-catch block and using the catch clauses to identify which exception it is?
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.