I'm an exception, let me out of here...

| 0 Comments

We're adding some new functionality to the refactoring project. Unfortunately the new functionality is located in the Heart of Darkness - the most twisty and poorly structured code in the whole system. Today I stumbled onto something truly awful. Exceptions used as glorified gotos within a 350 line function...

Exceptions are a great way of handling exceptional situations by hurling information up the call stack to someone who can deal with it better than you can. When used properly they allow the programmer to focus on the normal case and strip away masses of error handling code. I'd forgotten exactly how horrible code can be when they're used inappropriately.

Picture a cluster of 300+ line functions - you can take it as read that they're all trying to do far too much. In amongst the poorly named variables and ludicrously convoluted logic we have the only use of exceptions in the entire system. The functions start with a try block, do loads of stuff and occasionally bail out by throwing an exception. The exception is caught inside the same function and an error state is set and the function returns. The exceptions are just gotos by another name. It's like someone was flicking through a C++ text book and stumbled across a feature they hadn't yet used and felt they just had to try it out there and then...

Generally the error handling in the system is pretty poor. It mostly consists of a mix of message boxes that might pop up with cryptic clues or asserts that may fire. Generally when strange things happen the program simply barfs at the user and stumbles on until it eventually dies in some unrelated area of code. Much of the error handling could be simplified through the correct use of exceptions. Unfortunately this just adds more complexity to the mix.

Yet another entry on the list of non-trivial refactorings. Like most unnecessary complexity this will vanish by itself as the code around it is simplified. Unfortunately this code is some of the most twisty in the system so it may be a while before we have enough courage to tackle it. In the meantime, I'm praying that the original developer never got to the page on placement new...

Leave a comment