9.15.5. Stopwatch Example

Simula 67, the first object-oriented programming language, was created to simplify computer simulations. When modeling physical objects or intangible concepts, a software designer begins with a class representing the modeled object. The actions the modeled object can do are mapped to the class's operations and implemented as functions in a programming language. Map the data or information the object manages to the class's attributes and implement them as member variables. Sometimes it isn't clear if we should choose a variable, a function, or both. We can write a correct program in many ways, so we choose the easiest way in cases like these.

A picture of an analog stopwatch with two buttons and two hands on the display.
A stopwatch modeling example. A simple device like a stopwatch has enough features to make it a good modeling example without becoming overwhelming. It has three features that interest us: (1) a start/stop button, (2) a reset button, and (3) a display.

In this example, we will model a stopwatch with two buttons and a display. The display, formed by the two hands and the numbers, displays the elapsed time between starting and stopping the watch. When pressed, the button on the side resets the display to 0. The top button performs two different operations depending on the watch's state: If stopped, the watch starts; if running, the watch stops. In general, the state of an object is the object's current condition or what the object is doing (e.g., stopped or running).

The Stopwatch Class

We begin by analyzing the problem. The stopwatch does something or performs some behavior when the user presses either of the buttons. Therefore, it's easy to model the two buttons with operations or functions. For a console-based program, the display is a little less clear. It must manage the elapsed time, so an attribute or member variable is needed. If the program had a graphical user interface (a GUI), then the display would always be visible, but with a console-based program, we must add an operation to display the elapsed time on demand. So, we implement the display with an attribute (variable) and an operation (function) combination.

The design phase follows and builds on the analysis. The Stopwatch class currently specifies the three features we identified in the "real world." But as we design the program, we discover it needs two more member variables not identified during analysis and not present in the UML diagram. It's common for a program to require features (variables and functions) beyond those in the "real world." During the design phase, we add these features, called implementation features. We add a variable to store the time at which the Stopwatch object begins running. The time difference between when the watch stops and starts will give us the elapsed time. We also add a flag to represent the watch's state: running or stopped.

The first version of the Stopwatch UML class diagram:
Stopwatch
-----------------
-elapsed : double = 0
-----------------
+stime() : void
+reset() : void
+display() : void The second version Stopwatch UML class diagram:
Stopwatch
-----------------
-elapsed : double = 0
-stopped : bool = true
-timeb : start_time
-----------------
+stime() : void
+reset() : void
+display() : void
(a)(b)
The Stopwatch UML class diagram. The two UML class diagrams represent two phases of the software development process: analysis and design. (See also Class Development). The stime function models the button at the top of the stopwatch: pressing it once starts the watch running; pressing it again stops the watch. The reset function models the reset button to the right of the start/stop button; pressing it resets the time to zero. The display function displays the elapsed time.
  1. A Stopwatch UML class diagram created during analysis. Each member in the class diagram corresponds to a feature identified in the problem domain, i.e., in a physical stopwatch.
  2. A modified Stopwatch UML class diagram updated during design. The stopped and start_time member variables don't appear in the original, "real world" problem, but they are necessary for a software implementation.
When creating class diagrams, software developers attempt to make them independent of any programming language or operating system. Nevertheless, some data types (e.g., bool) are tied to specific languages while others (e.g., timeb) are tied to specific operating systems. Programmers must translate these types to match the implementing language and operating environment.

State Machines

UML class diagrams represent the static structure of an object-oriented program. They specify the data that instances of the class are responsible for maintaining and the operations they can perform. The diagrams form the skeleton or armature of an object-oriented program - every part of the program attaches to and builds on the diagrammed classes. Some classes also have dynamic behavior, which means that what they do next depends on what they have done in the past. The UML represents dynamic behavior with statechart diagrams based on rigidly specified state machines.

State machines often recognize data patterns or respond to events such as button presses. How we describe some parts of a state machine depends on its purpose. A basic state machine consists of just a few simple parts, each a finite set of elements:

A state machine with two states: Stopped and Running. Two arrows, both labeled with 'stime,' connect the states. Two arrows, labeled 'reset' and 'display,' leave from and return to the 'Stopped' state.
The Stopwatch state machine. Two states fully characterize a Stopwatch object. The black dot with an arrow to the Stopped state designates Stopped as the initial or starting state. Two transitions leave and return to the Stopped state. These self-transitions respond to the corresponding button presses, complete the actions (i.e., call the named functions), and return to the Stopped state. A pair of transitions join the Stopped and Running states. Pressing the stime button triggers each transition, which causes the object to run its stime() function.

System Calls

When a program needs a service that doesn't have a language-specific operation, it must use a system call. Such is the case with the stopwatch program, where we need to get timing information. We use a system call that returns the amount of time since the epoch, the beginning of time for the computer. For Unix, Linux, and macOS systems, the epoch is January 1, 1970; for Windows systems, the epoch is January 1, 1980. In practice, the program defines a structure with two integer fields: time and millitm. The first field is the number of whole seconds since the epoch, and the second field is the number of milliseconds. The program passes the structure by-pointer in the system call, and the operating system fills the structure.

  Structure System Call
Windows_timeb_ftime_s
Unix
Linux
MacOS
timebftime
Getting the time since the epoch. The structures and the system calls needed to get the time since the epoch varies between operating systems, but the same include directive incorporates them into a program: #include <sys/timeb.h>

Elaborated Source Code

The third phase of the software design process is implementation or programming. In a "real world" situation, it's common for a customer to provide us with a set of requirements to which we must adhere. We don't have formal requirements or a physical watch to model, so we are free to adopt two arbitrary behaviors. First, it may be difficult to reset the time if a mechanical watch is running. So, in that case, we'll choose to do nothing. Second, a mechanical watch continuously displays the elapsed time. We could duplicate that behavior with a GUI program, but not one based on the console. So, we choose only to show the time when the watch is stopped. If a problem specifies a particular behavior, we must follow the requirement; otherwise, we can choose how to implement an operation. If we do have a customer, we should get approval (in writing) for our choices.

#include <iostream>
#include <sys/timeb.h>
using namespace std;


class Stopwatch
{
    private:
        double      elapsed = 0;
        bool        stopped = true;
        _timeb      start_time;                    // Windows
        //timeb     start_time;                    // Linux


    public:
        //Stopwatch() : elapsed(0), stopped(true) {}


        void reset()
        {
            if (stopped)
                elapsed = 0;
        }


        void stime()
        {
            if (stopped)
            {
                _ftime_s(&start_time);          // Windows
                //ftime(&start_time);           // Linux
                stopped = false;
            }
            else
            {
                _timeb    end_time;              // Windows
                _ftime_s(&end_time);
                //timeb    end_time;             // Linux
                //ftime(&end_time);
                elapsed +=
                    floattime(end_time) - floattime(start_time);
                stopped = true;
            }
        }


        void display()
        {
            if (stopped)
                cout << "-------------" << endl << elapsed
                    << endl << "-------------" << endl;
        }


    private:
        double    floattime(_timeb t)             // Windows
        //double  floattime(timeb t)              // Linux
        {
            return t.time + t.millitm / 1000.0;
        }
};


int main()
{
    Stopwatch   sw;
    char        op;

    do
    {
        cout << "S\tStart/Stop" << endl;
        cout << "D\tDisplay" << endl;
        cout << "R\tReset" << endl;
        cout << "E\tExit" << endl;

        cin >> op;
        cin.ignore();

        switch (op)
        {
            case 'S' :
            case 's' :
                sw.stime();
                break;

            case 'D' :
            case 'd' :
                sw.display();
                break;

            case 'R' :
            case 'r' :
                sw.reset();
                break;

            case 'E' :
            case 'e' :
                break;

            default:
                cerr << "Unrecognized operation" << endl;
                break;
        }

    } while (op != 'E' && op != 'e');

    return 0;
}

Downloadable Code

stopwatch.cpp