The above code leaves much to be desired. This is what I wanted to improve
We can use the visitor pattern to dynamically choose the right algorithm based on the events type.
This refactor makes the code easier to read and maintain.
For example, in the previous implementation each if statement would increase the cyclomatic complexity by 1. The refactor has made the cyclomatic complexity of the catch clause 1 for any number of exceptions.
The solutions we created needs to be supported by code specifically designed to facilitate the visitor pattern.
The function addExceptionHandlingVisitor acts as a decorator for our custom Errors. It’s purpose is to allow each error module to visit an error handler. It does this by attaching a visit function to any module that is passed to it.
In the code above, The visit function expect an exception handling module (i.e. context). The context variable is expected to have two function: test and handle. The test function is expected to inform the visitor whether or not it is a handler for the error, and the handle function is expected to actually handle the error.
Consider the following implementations of handlers for DuplicateUsernameError and CreditCardRejectedError.
Note: We could refactor this to have an inheritance hierarchy with reusable code, but I don’t believe that their would be much benefit in going to that effort.
A working example is also located on my jsfiddle account:
If you find yourself writing a lot of conditional logic in single place then that should set an alarm in your head that reminds you to simplify your code with the use of polymorphism. Simplifying complicated conditional logic like nested if-else statements is exactly why polymorphism was invented.