Removing details in an algorithm
Imagine that you are sitting in a chair in your home when someone knocks at the door. What do you do? How do you react to this event?
Common answers to this scenario apply a great amount of abstraction—“removing—or obscuring—detail”:
- Open the door leaves out how you get to the door
- Adding walk to the door doesn’t explain how to actually walk
- Replace walk to the door with a repeated series of take a step doesn’t describe how steps are taken
- Lift your foot leaves out which muscles you use to bend your leg
In fact, at some level, your body adds layers of abstraction. After all, you are not aware of all of the molecular processes needed to perform the seemingly simple task of contracting a muscle.
To walk is a common occurrence. Wouldn’t it be nice to define walking—with all of the necessary details—once and then just call it walk? After all, listing all of the actions needed to perform such a simple task every time you did it would be annoying and time-consuming.
A procedure is a named collection of steps in an algorithm that can be reused anytime it is needed. A procedure is an abstraction because the details of how it is performed are only defined once. Repeated use of the procedure then ignores the details that define it.
PROCEDURE walk 1. Lift left leg. 2. Move left leg forward. 3. Set left leg down. 4. Lift right leg. 5. Move right leg forward. 6. Set right leg down.
The procedure defined in the last section, walk, is problematic. It only consists of two steps. In reality, we’d like to define walk so that we can take any number of steps. Instead of defining separate procedures take 1 step, take 2 steps, take 3 steps, etc., we can apply abstraction again—“removing detail”—to create a procedure take n steps, so that n can be whatever we want it to be each time we use it.
Notice that the value n can vary, and we can create instructions with it without knowing what it is. This means that it is, in effect, a variable. It’s a special type of variable called a parameter. It is only relevant within the procedure in which it is defined.
Using this parameter n, we can rewrite our procedure as:
PROCEDURE take n steps REPEAT n times 1. Lift left leg. 2. Move left leg forward. 3. Set left leg down. 4. Lift right leg. 5. Move right leg forward. 6. Set right leg down.