user2684198
user2684198

Reputation: 852

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)

Upvotes: 2

Views: 631

Answers (3)

Gfalco
Gfalco

Reputation: 87

Where you get the exception you define a map Map<String, ExceptionHandler> and call something like this:

Optional.of(stringExceptionMap.get(throwable.getClass().getSimpleName()))
                                 .map(errorHandlers -> errorHandlers.handle(throwable).orElseGet(() ->  whatever));  

where

public interface ExceptionHandler {

    T handle(Throwable throwable);
}

have strategies like

@Component("WebExchangeBindException")
public class WebExchangeBindExceptionErrorsExtractor implements ErrorsExtractor {

    @Override
    public T handle(Throwable throwable) { ... } 
}

Upvotes: 1

Chris Gerken
Chris Gerken

Reputation: 16392

What about throwing the exception in a try-catch block and using the catch clauses to identify which exception it is?

Upvotes: 1

GhostCat
GhostCat

Reputation: 140457

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.

Upvotes: 3

Related Questions