Skip to Main Content
The Art of Readable Code
book

The Art of Readable Code

by Dustin Boswell, Trevor Foucher
November 2011
Intermediate to advanced content levelIntermediate to advanced
206 pages
4h 32m
English
O'Reilly Media, Inc.
Content preview from The Art of Readable Code

Chapter 15. Designing and Implementing a “Minute/Hour Counter”

image with no caption

Let’s take a look at a data structure used in real production code: a “minute/hour counter.” We’ll take you through the natural thought process an engineer might go through, first trying to solve this problem and then improving its performance and adding features. Most important, we’ll also be trying to keep the code easy to read, using principles from throughout this book. We might take some wrong turns along the way or make other mistakes. See if you can follow along and catch them.

The Problem

We need to keep track of how many bytes a web server has transferred over the past minute and over the past hour. Here’s an illustration of how these totals are maintained:

image with no caption

It’s a fairly straightforward problem, but as you’ll see, solving it efficiently is an interesting challenge. Let’s start by defining the class interface.

Defining the Class Interface

Here is our first version of the class interface in C++:

class MinuteHourCounter {
  public:
    // Add a count
    void Count(int num_bytes);

    // Return the count over this minute
    int MinuteCount();

    // Return the count over this hour
    int HourCount();
};

Before we implement this class, let’s go through the names and comments to see if there’s anything we want to change.

Improving the Names

The class ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Five Lines of Code

Five Lines of Code

Christian Clausen
The Art of Clean Code

The Art of Clean Code

Christian Mayer

Publisher Resources

ISBN: 9781449318482Errata Page