Beacon's pseudocode now fills four pages. Comet flips through it, looking for the light check.
"Here is the water average," she says. "And here is the light average. And the temperature average."
Wren lays the three pages side by side. "What do you notice?"
Comet squints. "They are the same eight lines. Only the list name changes."
"And when you fixed a bug in one copy last week," Wren says, "did you fix the other two?"
Comet groans. She did not.
Nova hovers over the pages. "Would you like a hint?" she asks.
"Give those eight lines a name. Then Beacon can call them whenever it needs an average."
How do programmers split a big problem into pieces they can reuse?
This week you will write procedures for Beacon, plan its modules and look at shared code with care.
A procedure is a named group of programming instructions. It may have parameters and return values.
Different languages use different names for procedures, such as method or function.
Once a procedure is written and tested, you can call it by name as many times as you like.
Building on existing correct algorithms saves time. It reduces development time, reduces testing and makes errors easier to find.
PROCEDURE average(numbers)
{
total ← 0
count ← 0
FOR EACH num IN numbers
{
total ← total + num
count ← count + 1
}
RETURN(total / count)
} The name of this procedure is average. Its parameter, numbers, is the list it works on.
RETURN sends the answer back to whatever line called the procedure.
| Before: three copies | After: one procedure |
|---|---|
| Eight lines for the water average | waterAverage gets average(waterReadings) |
| Eight lines for the light average | lightAverage gets average(lightReadings) |
| Eight lines for the temperature average | tempAverage gets average(tempReadings) |
| A bug must be fixed three times | A bug is fixed once, in one place |
| Statement | True or false? |
|---|---|
| A procedure is a named group of programming instructions. | ? |
| Some languages call procedures methods or functions. | ? |
| A procedure can be called only once in a program. | ? |
| Reusing a tested procedure can reduce testing time. | ? |
Strong start, developer. Tomorrow you will call procedures with arguments and trace their return values.