Friday, December 24, 2010

Handling Failure

Here are two coding styles for handling failure. I read a lot of code that uses the first. I always use the second.

(1)

do-something;

if (success) {
do-this;
do-that;
...
[many lines of stuff]
do-some-other-thing;
}
else
{
print-error-message-and-exit;
}

(2)

do-something;

if (failure) {
print-error-message-and-exit;
}

do-this;
do-that;
...
[many lines of stuff]
do-some-other-thing;

I could go on at length to try to justify my strong preference, but I won't. In the end, it's just taste.

No, I take it back, I will rationalize a little. Here are some reasons I prefer #2.

  • It's shorter overall.
  • The short alternative comes first, so you don't overlook it in the noise.
  • There's one fewer nesting level to puzzle through. This also occasionally permits longer lines without word-wrap.
  • It feels more like exception handling, and saying what I mean: A problem? Let's bail.
In Perl, the solution is even more stereotyped and easy-to-read:
do-something OR die "it didn't work";
...
In bash, I use a shell function, die(), which I wrote to let me code in the same style:
do-something || die "It didn't work"
...

2 comments:

Anonymous said...

I'm right with you here. I also think very carefully about the best way to structure "if" sorts of sequences:

Should I do "if x" or "if not x"? Does one make more sense, is one going to be shorter?

Do I do an "else" or can I exit/break/return/exception in my "if"?

It really helps readability.

I'll admit though that I really am not a fan of "x or die". It feel like the important thing ends up in the middle of the line then, and we read left to right, so it's easy to miss. I think "if not x: die" makes it more obvious at the left hand side, where we start reading, that there is more going on here.

"x unless y" also drives me crazy for similar reasons.

Syntax highlighting REALLY helps out here, but if you're stuck without it you really have to be careful about scanning code.

jed said...

I recall, when I got into the IT business (back then, we called it 'DP'), there was a guy on the team who as fanatic about goto-less programming. While I understand avoiding spaghetti code, I always thought it was more readable to avoid the heavy nesting required to write complex choice structures without gotos. (This was COBOL). I didn't use them much, but bailing out of a loop or if block by issuing a forward goto to the end-of-paragraph never bothered me, and IMHO made for code that was much more readable and easy to follow. I used it as a break statement.

I had one manager who strongly advised against using condition negation, on the ground that it was more difficult to grasp the logic. This might be true as a general case. I recall reading about academic tests, that students tend to have more trouble with questions worded using negation.

Syntax highlighting drives me nuts.