You are currently browsing the monthly archive for January 2007.

Call me crazy, but I think Peter Stormare (of the new Volkwagen Unpimp Your Ride commercials) looks a lot like Ralph Johnson. What do you think?

Peter Stormare Ralph Johnson

Advertisements

I was looking at Doug Ross’s blog the other day; in particular his beef with exception-based programming. I definitely have more C++ experience than Java, so whenever I think about exceptions I think in the context of exception safety, transactional semantics, and RAII. Here’s my take on what he said:

Exceptions tacitly encourage abdication of cleanup responsibility… But the problem is, very few people are disciplined enough to set try, catch and finally clauses for every single method.

I would never expect every single method to have a try/catch/finally block associated with it. In my opinion, that’s a waste of the exception model, and severely limits its advantages. When I layer code, I want to consider sources (in the dark hearts of libraries) and sinks (in the application interface or controller) of exceptions. I try to minimize the exception handling (try/catch/finally) performed anywhere in between.

Wait! How can less exception handling produce better results? In C++ at least, the answer is “stack management”. Local objects (anything not allocated with new) are created on the stack. If an exception occurs, the stack is unwound, calling destructors for all instantiated local objects. If all of my setup code occurs in C++ object constructors, and all of my teardown code occurs in the object destructors, then the compiler will essentially write my try/catch/finally itself. I don’t have to worry about setting flags for what teardown needs to complete; that information is implied by the objects on the stack.

Now, code has transformed from this:

try {
    file = open(myFileName);
    file.readInto(myDataStructure);
finally {
    if (file) file.close();
}

to this:

openFile(myFileName);
openFile.getFileObject().readInto(myDataStructure)

If readInto raises an exception, the destructor of openFile will close the file properly, and I don’t need to worry about it whenever I try to use files. There’s definitely a benefit to be able to avoid this boilerplate checking. The associated cost, then, is creating objects like openFile that act as sentries on my stack. Read the rest of this entry »