O'Reilly logo

The Art of Readable Code by Trevor Foucher, Dustin Boswell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Larger Example

In a web-crawling system we built, a function named UpdateCounts() was called to increment various statistics after each web page was downloaded:

void UpdateCounts(HttpDownload hd) {
    counts["Exit State"   ][hd.exit_state()]++;      // e.g. "SUCCESS" or "FAILURE"
    counts["Http Response"][hd.http_response()]++;   // e.g. "404 NOT FOUND"
    counts["Content-Type" ][hd.content_type()]++;    // e.g. "text/html"
}

Well, that’s how we wish the code looked!

In actuality, the HttpDownload object had none of the methods shown here. Instead, HttpDownload was a very large and complex class, with many nested classes, and we had to fish out those values ourselves. To make matters worse, sometimes those values were missing altogether—in which case we just used "unknown" as the default value.

Because of all this, the real code was quite a mess:

// WARNING: DO NOT STARE DIRECTLY AT THIS CODE FOR EXTENDED PERIODS OF TIME.
void UpdateCounts(HttpDownload hd) {
    // Figure out the Exit State, if available.
    if (!hd.has_event_log() || !hd.event_log().has_exit_state()) {
        counts["Exit State"]["unknown"]++;
    } else {
        string state_str = ExitStateTypeName(hd.event_log().exit_state());
        counts["Exit State"][state_str]++;
    }

    // If there are no HTTP headers at all, use "unknown" for the remaining elements.
    if (!hd.has_http_headers()) {
        counts["Http Response"]["unknown"]++;
        counts["Content-Type"]["unknown"]++; return; } HttpHeaders headers = hd.http_headers(); // Log the HTTP response, if known, otherwise log "unknown" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required