The Artima Developer Community
Sponsored Link

Programming Defensively
A Conversation with Andy Hunt and Dave Thomas, Part IX
by Bill Venners
April 28, 2003

<<  Page 2 of 3  >>


Crash Early

Bill Venners: In your book you suggest we try to detect problems as early as possible, so we can make the program crash before it does damage. I have often felt the need for a ShouldNeverHappenException in Java. I'm programming along, and I get to a case that I'm confident will really never happen. But just in case it ever happens, I want to throw an exception there, but what exception? I usually end up throwing a RuntimeException and putting in a comment that "This should never happen." But it takes time to add that throw statement, as does any way of crashing early. Checking every pointer in a C program for null before it's used, for instance, would take a lot of time. Where do you draw the line? How do you decide the investment is worth it?

Dave Thomas: That's interesting, because quite often you don't have to do anything special to crash early. For example, as long as you're sure a nullpointer is going to cause an error immediately, then I don't see much difference in throwing a random RuntimeException or throwing a NullPointerException. The bad thing is to propagate an error.

The reason you crash early is to stop errors from propagating far away from the cause. Because once you have an error that's a million instructions away from the cause, finding the cause is a pain in the butt. Quite often, the check is done for you by the compiler. What we're trying to say is when the checks are not put in by the compiler, that's when you start needing to put the checks in yourself.

Andy Hunt: It's more an issue of localization, keeping the crash near the cause.

Bill Venners: You write in your book, "When the system does fail, will it fail gracefully?" And in a footnote, you write, "Our editors wanted us to change this sentence to, 'If the system does fail...' We resisted." Why?

Andy Hunt: We actually quite deliberately put in "When." I think we had this argument in a draft of the book. Somebody else reading the draft made the same comment, that we should say, " If the system fails..." No, that's wrong. It should be, "When the system fails..." Every system fails. There is no such thing as perfect software. So part of phrasing that sentence that way is to encourage people to get over this in-bred arrogance that the system can't fail. Of course it can. Every system can fail. The question should not be, "Can the system fail?" It should be, "When the system fails, how are you going to handle it?"

<<  Page 2 of 3  >>

Sponsored Links

Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us