How to Design Programs: An Introduction to Computing and Programming
When we design a program to control a traffic light, we probably don't want to control just one traffic light, but several.
Similarly, when we design a program to manage names and phone numbers, we might wish to manage several address
books, not just one. Of course, we could copy the code for a traffic light controller (or an address book manager) and
rename the state variables, but copying code is bad. Furthermore, we might wish to create so many traffic lights that
copying code is plain impractical.
The proper solution is to use the power of abstraction. Here we abstract over several instances of the address book
program and the traffic light program and so on. This differs from the notion of abstraction in part
because it involves
state variables, but the idea and even the technique is the same. We encapsulate the state variables and the functions in a
-expression and thus give ourselves the power to create as many versions as necessary. We learn how to encapsulate
state variables in the first subsection, and practice it in the second one.
Abstracting with State Variables
Suppose we wish to turn the program in figure
) into a program for managing (simulated) traffic lights. An
operator of the simulation should be able to control each traffic light independently of the others. Indeed, the operator
should be able to add or shut down traffic lights while the rest of the system remains unchanged and running.
Based on our experience, we know that each traffic light in the simulation requires two definitions:
a state variable,
, which keeps track of the light's current color; and
a service function,
, which switches the traffic light to the next color according to the traffic laws.
For a graphical simulation, the service function would also redraw the traffic light so that users can view the current
color. Finally, each traffic light has a unique location on the canvas:
[Multiple Traffic Lights]
The sample program of figure
deals with a single traffic light and lacks the drawing operation. The problem now is
to turn this into a program that can create as many traffic lights as needed, each with its own state variables and
switching functions and at its own location. If we were to copy the definitions in figure
and add definitions for
dealing with the canvas, the various instances would differ in only one aspect: the data concerning the location of the
traffic light. This thought experiment suggests that we should develop an abstract function that creates and manages
traffic lights at various locations.
Because the original program consists of several top-level definitions, we use the recipe of section