Developing Procedures
How to write your own procedures, and why breaking a program into named procedures with parameters makes it shorter, easier to read, easier to fix, and easier to improve.
1Know what, not how
Procedural abstraction gives a name to a process and lets anyone use the procedure knowing only what it does, not how it does it. You use LENGTH(aList) and DISPLAY all the time without knowing their insides. When you write your own procedures, the rest of your program gets the same benefit.
Abstraction is a way of managing complexity: it hides details you don't need at the moment, so you can think about the problem in bigger pieces.
2Big problems, small procedures
Procedural abstraction lets the solution to a large problem be built from the solutions to smaller subproblems, with one procedure for each. Dividing a program into separate subprograms like this is called modularity.
PROCEDURE countCorrect(answers, key)
{
correct ← 0
i ← 1
REPEAT LENGTH(key) TIMES
{
IF (answers[i] = key[i])
{
correct ← correct + 1
}
i ← i + 1
}
RETURN(correct)
}
PROCEDURE percent(part, whole)
{
RETURN(part * 100 / whole)
}
PROCEDURE letterGrade(pct)
{
IF (pct ≥ 90)
{
RETURN("A")
}
IF (pct ≥ 80)
{
RETURN("B")
}
IF (pct ≥ 70)
{
RETURN("C")
}
RETURN("F")
}
With those three procedures written, the main program reads almost like a sentence:
right ← countCorrect(answers, key) pct ← percent(right, LENGTH(key)) DISPLAY(letterGrade(pct))
For answers B, D, C, A, C against the key B, D, A, A, C, right is 4, pct is 80, and the program displays B. If grades come out wrong, you can test letterGrade alone with a few percentages instead of reading the whole program.
3One procedure instead of copies
A procedural abstraction can pull out the shared part of repeated code so it is written once and reused. These lines find three class averages by copying the same steps three times:
total ← 0
FOR EACH s IN mathScores
{
total ← total + s
}
DISPLAY(total / LENGTH(mathScores))
total ← 0
FOR EACH s IN sciScores
{
total ← total + s
}
DISPLAY(total / LENGTH(sciScores))
total ← 0
FOR EACH s IN artScores
{
total ← total + s
}
DISPLAY(total / LENGTH(artScores))
PROCEDURE average(scores)
{
total ← 0
FOR EACH s IN scores
{
total ← total + s
}
RETURN(total / LENGTH(scores))
}
DISPLAY(average(mathScores))
DISPLAY(average(sciScores))
DISPLAY(average(artScores))
Both versions display 83 91 80. The second is shorter, easier to read (the name average says what is happening), and if the averaging needs to change, say to round the result, there is one place to fix instead of three. Reusing code instead of copying it is one of the main ways procedures manage complexity.
4Parameters make procedures general
Parameters let one procedure handle a whole range of inputs. Without them you end up with near-identical procedures that differ in one number:
PROCEDURE withStateTax(price)
{
RETURN(price + price * 6 / 100)
}
PROCEDURE withCityTax(price)
{
RETURN(price + price * 8 / 100)
}
PROCEDURE withTax(price, ratePercent)
{
RETURN(price + price * ratePercent / 100)
}
The rate that was built into each copy has become a parameter. withTax(50, 6) gives 53, the same as withStateTax(50), and withTax(50, 10) gives 55 for a rate neither old procedure could handle. A program checked that the general version matches both old ones on several prices.
Procedures manage complexity: they name a process so it can be used without knowing how it works, split big problems into smaller subproblems (modularity), replace copied code with one reusable definition, become general through parameters, and make programs easier to read.
5Changing the inside
Because callers rely only on what a procedure does, a programmer can change its insides, to make it faster, use less memory, or fix a bug, without telling anyone who uses it, as long as what it does stays the same.
PROCEDURE sumTo(n)
{
total ← 0
k ← 1
REPEAT n TIMES
{
total ← total + k
k ← k + 1
}
RETURN(total)
}
PROCEDURE sumTo(n)
{
RETURN(n * (n + 1) / 2)
}
DISPLAY(sumTo(10)) DISPLAY(sumTo(100))
Both versions display 55 and 5050; a program checked that they agree for every n from 0 to 300. Version 2 is far faster for large n, and nothing in the calling program had to change. If version 2 had returned a different result, every caller would have been affected; that is the promise a procedure must keep.
6Writing a procedure
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
}
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
RETURN(expression)
}
A procedure can take zero or more parameters. RETURN is optional and can appear anywhere inside; when it runs, the procedure ends immediately and control goes back to the calling statement. Writing one means three decisions:
| Decision | Question to ask | isEven | showAll |
|---|---|---|---|
| Name | What does it do, in a few words? | isEven (a yes/no question) | showAll (an action) |
| Parameters | What does it need to be told? | the number | the list |
| RETURN or effect | Does it produce a value, or do something? | returns true or false | displays; returns nothing |
PROCEDURE isEven(n)
{
RETURN(n MOD 2 = 0)
}
DISPLAY(isEven(14))
DISPLAY(isEven(9))
PROCEDURE showAll(names)
{
FOR EACH name IN names
{
DISPLAY(name)
}
}
showAll(["Ruth", "Omar", "Kai"])
These display true false and Ruth Omar Kai. If a procedure computes something other code may need, RETURN the value and let the caller decide whether to display it.
Where RETURN goes matters. To check whether a list contains a value, return true as soon as you find it, and return false only after the loop has checked everything:
PROCEDURE contains(aList, target)
{
FOR EACH item IN aList
{
IF (item = target)
{
RETURN(true)
}
}
RETURN(false)
}
PROCEDURE contains(aList, target)
{
FOR EACH item IN aList
{
IF (item = target)
{
RETURN(true)
}
ELSE
{
RETURN(false)
}
}
}
| Call | Correct version | Early-return version |
|---|---|---|
contains([4, 9, 2, 7], 7) | true | false |
contains([4, 9, 2, 7], 4) | true | true |
contains([4, 9, 2, 7], 5) | false | false |
The second version returns on the very first element either way, so it only ever looks at element 1. It gets 7 wrong. It happens to give the right answer for 4 and 5, which is why testing with only one or two inputs can miss this bug.
7Worked examples
The larger of two
Write maxOf(a, b), which returns the larger of two numbers.
- 1Name given; two parameters; it produces a value, so it needs RETURN.
- 2If
a > b, return a. Otherwise the code reaches the last line and returns b:PROCEDURE maxOf(a, b) { IF (a > b) { RETURN(a) } RETURN(b) } - 3Test both orders and a tie: maxOf(3, 8) is 8, maxOf(8, 3) is 8, maxOf(5, 5) is 5.
Comparing two classes
A program needs to know which of two classes has the higher average. Why can't it use this procedure?
PROCEDURE showAverage(scores)
{
total ← 0
FOR EACH s IN scores
{
total ← total + s
}
DISPLAY(total / LENGTH(scores))
}
- 1
showAveragedisplays the average but returns nothing. - 2So
x ← showAverage([80, 90])shows 85 on the screen but leavesxwith no value, and there is nothing to compare. - 3The
averageprocedure from section 3 returns the value, soIF (average([80, 90]) > average([70, 95]))works.
Count any value
A program has countYes(votes) and countNo(votes), identical except for the word they look for. Replace them with one procedure.
- 1The difference between the two is the target word, so make it a parameter.
- 2Write the shared steps once:
PROCEDURE countOf(aList, target) { count ← 0 FOR EACH item IN aList { IF (item = target) { count ← count + 1 } } RETURN(count) } votes ← ["yes", "no", "yes", "yes", "no"] DISPLAY(countOf(votes, "yes")) DISPLAY(countOf(votes, "maybe"))
3 0, and the same procedure can now count any value in any list.Why procedures?
A student replaces 40 lines of a game with calls to moveEnemy, checkCollision, and updateScore. Explain two ways this manages complexity.
- 1Modularity: each procedure solves one smaller subproblem and can be written and tested on its own; a scoring bug means opening
updateScoreonly. - 2Readability and abstraction: the main loop now says what happens each turn in three named steps, without the details of how.
- 3If
checkCollisionis later made faster, the main loop does not change, as long as it still reports collisions the same way.
8Common mistakes
A RETURN in both branches of an IF inside a loop ends the procedure on the first pass. The “not found” RETURN goes after the loop.
If other code needs the result, RETURN it. A displayed value cannot be stored or compared.
Near-identical procedures are a sign that the changing value should be a parameter.
The inside can change freely only if the results stay the same. Change the results and every caller is affected.
“The procedure average(scores) replaces three copies of the same loop. Because scores is a parameter, one definition works for any class's list, and a change to how averages are computed is made in one place instead of three. The calls also make the program easier to read.”
Name the procedure, say what repeated work or subproblem it handles, and connect it to reuse, parameters, readability, or modularity.