Sunday, August 31, 2008

Eschew Case Analysis

It ticks me off when I see code like this:
if (str != NULL && *str != '\0') {
exists = true;
}
else {
exists = false;
}

This is a pretty simplistic example, and most -- not all! -- programmers would get rid of the exists variable and the accompanying code, and replace it all with (str && *str). But it's all too common to find more subtle versions of this same kind of logic bloat. And when it's even more complicated and nested... can you say "cyclomatic complexity"?

This is a special case of what Dijkstra very cogently described as "spurious case analysis". That link is well worth reading, by the way.

Dijkstra was certainly on the science side of the engineering-science frontier. I once heard him say that the world would be a better place if all computer programs had to be chiseled in marble. I don't agree with that, but his commandment to avoid case analysis resonates with good software engineering practice: be concise, self-document, code for testability.

If you can avoid case analysis, do so. Otherwise....

No comments: