Sub-programs, Pre- and Post-conditions, Testing and Debugging

IB Computer Science · Computational Thinking, Problem-Solving and Programming

Sub-programs and their contracts. A sub-program (procedure or function) packages a task behind a name and a list of parameters. It is worth writing when the same steps are needed in more than one place, when a long program becomes readable only if split into named parts, or when a part can be tested on its own. Each sub-program has a contract: a pre-condition, what must be true before it is called (the array is sorted; N is positive), and a post-condition, what is guaranteed afterwards (returns the index of the item or −1). Binary search's pre-condition is the reason it fails silently on unsorted data: the contract was broken by the caller, not by the algorithm. Stating contracts is how large programs are built by many people without each reading the others' code.

Parameters and scope. A parameter passed by value gives the sub-program a copy, so changes inside do not affect the caller; passed by reference, the sub-program works on the original, which is how a sort routine modifies the caller's array. A local variable exists only inside the sub-program; a global one is visible everywhere, which is convenient and dangerous, because any sub-program can change it and the reason for a wrong value becomes impossible to trace. Prefer parameters and return values; use globals only for true constants.

Choosing test data. Testing shows the presence of errors, never their absence, so data must be chosen to make errors hard to hide. Three categories: normal data inside the expected range (a mark of 50); boundary data on and beside each limit (0, 1, 99, 100), where off-by-one errors live; and erroneous data outside the range or of the wrong type (−1, 101, 50.5, text, empty), which the program must reject without crashing. Add the empty case and the single-item case for every loop and every array. For each test, write the expected output before running, or the test proves nothing.

Finding the bug. When output is wrong: shrink the input to the smallest case that still fails (N = 3, not N = 1 000); trace by hand with one column per variable and one row per step; compare the actual column with the expected column, and the first row where they diverge is where the bug is; fix it; then rerun every earlier test, because a fix that breaks something else is common. Typical bugs to recognise on sight: a loop bound one too high or too low; a variable initialised in the wrong place; using the wrong comparison (less than versus less than or equal); integer division where real division was meant; updating a maximum without its position; and reading a variable before it has been assigned.

TESTING: THREE TYPES OF DATA — AND A TRACE TABLE TO FIND ERRORS rule: a valid score is an integer from 0 to 100 0 100 NORMAL: 50, 73 BOUNDARY: 0, 1 BOUNDARY: 99, 100 SAI: -1 SAI: 101 INVALID of another type: 50.5 · "abc" · blank cell · 1e9 errors like to hide at the boundary: writing less than 100 instead of less than or equal to TRACE TABLE to find the error: sum 1..N I = 1 · SUM = 0 · loop while I ≤ N: SUM = SUM + I · I = I + 1 step I I ≤ 3? SUM ghi chú 01—0initialize 12correct1 23correct3 34correct6 44sai6exit, correct change ≤ to less than: stops at SUM = 3 → missing one iteration (off-by-one) PROCEDURE WHEN THE RESULT IS WRONG 1. find the SMALLEST data that reproduces the error (N = 3 instead of N = 1000) · 2. trace by hand line by line 3. compare the actual column with the expected column, the first line that differs is where the error is · 4. fix, then rerun ALL the old test cases precondition: what must be true BEFORE the call (array sorted) · postcondition: what is certainly true AFTER (returns an index or -1) testing proves there IS an error, never that there is NO error — so choose data that makes errors hard to hide
The figure on the left draws three types of test data on a number line for the rule that a valid score is an integer from 0 to 100. Normal data such as 50 or 73 lies in the middle of the range and checks that the program works in the common case. Boundary data is 0, 1, 99, 100 — the values on and right next to the limits — because errors like to hide there; for example, writing less than 100 instead of less than or equal to 100 will reject a perfect score. Invalid data includes −1 and 101 outside the range, and also wrong-type data such as decimals, letters, blank cells or very large numbers; the program must reject them in a controlled way rather than crash. The box on the right is a trace table used to find an error in a loop that computes the sum from 1 to N with N equal to 3: each row is a step, each column is a variable or a condition, and the last row shows the condition false so it exits with the correct sum of 6. If the condition is written as less than instead of less than or equal to, the table stops at a sum of 3 and exposes the missing-iteration error. The bottom box is the procedure when the result is wrong — find the smallest data that reproduces the error, trace by hand, compare the actual column with the expected one to find the first differing row, then fix and rerun all the old cases — along with the definitions of precondition and postcondition. The last line is the underlying principle: testing proves that there is an error but never proves that there is none.

Worked example: Example 1 — finding an error in an average-score algorithm using a trace table

The following algorithm computes the average of an array A with N elements but gives a wrong result: SUM = 0; loop I from 1 to N; SUM = SUM + A[I]; end loop; AVG = SUM div N; output AVG. With A = [10, 20, 30], N = 3, the expected result is 20. Find the error by tracing and fix it.

Solution

Step 1 — the smallest case. N = 3 is already small enough. Expected: SUM = 60, AVG = 20.

Step 2 — trace. Array indices start from 0 so A[0] = 10, A[1] = 20, A[2] = 30, and A[3] does not exist. I = 1: SUM = 0 + A[1] = 20. I = 2: SUM = 20 + A[2] = 50. I = 3: SUM = 50 + A[3] — out of array bounds; depending on the language, the program crashes or adds a garbage value. The first row that differs from the expectation is right at I = 1: expected SUM = 10 (A[0]) but actually 20. The error is at the loop boundary: it must run from 0 to N − 1.

Step 3 — a second error hidden behind the first. After fixing the loop, SUM = 60 and AVG = 60 div 3 = 20 — correct for this case. But try A = [10, 20, 25]: SUM = 55, 55 div 3 = 18 instead of 18.33. The div operation is integer division; an average needs real division. The first test case happened to divide evenly and so hid this error — an illustration of why one correct case does not prove the program correct.

Step 4 — the remaining boundary cases. N = 0: division by 0. The algorithm needs a precondition that N is greater than 0, or a branch that checks and reports an error. N = 1: SUM = A[0], AVG = A[0], correct.

The fix. if N = 0 then output "empty" else SUM = 0; loop I from 0 to N − 1; SUM = SUM + A[I]; end loop; AVG = SUM / N; output AVG; end if. Rerun all three cases: [10, 20, 30] → 20; [10, 20, 25] → 18.33; [] → "empty".

Worked example: Example 2 — designing subprograms with a clear contract and choosing how to pass parameters

A library management program needs: (a) a function to find the position of a book code in a sorted array of codes; (b) a procedure to sort the array of codes; (c) a function to compute the late fee from a number of days. For each, write the precondition and postcondition, choose pass by value or by reference, and state why global variables are not used.

Solution

(a) FIND(CODES, N, TARGET) returns an integer. Precondition: CODES is sorted in ascending order, N is the real number of elements, N ≥ 0. Postcondition: returns the index I with CODES[I] = TARGET if it exists, otherwise −1; the array is not changed. Since the function only reads, passing CODES by reference is acceptable to avoid copying a large array, but the postcondition must record that it does not modify it. The sorted precondition is what permits the use of binary search; if the caller violates it, the result is wrong with no message — so the caller is responsible.

(b) SORT(CODES, N) procedure. Precondition: N ≥ 0. Postcondition: CODES contains the same elements as before, in ascending order. It must be passed by reference, because the purpose is to modify the caller's array; passing by value would sort a copy and then throw it away — the classic error that makes the program appear to run while the array is unchanged. The postcondition same elements matters: a sorting procedure that loses or duplicates elements can still give an ascending array.

(c) FINE(DAYS) returns a real number. Precondition: DAYS is an integer ≥ 0. Postcondition: returns 0 if DAYS ≤ GRACE, otherwise (DAYS − GRACE) × RATE, not exceeding MAXFINE. Passed by value because only the number is needed. GRACE, RATE, MAXFINE are global constants — the only case where globals are reasonable.

Why not use global variables for data. If CODES is global and both FIND and SORT touch it, a wrong value could be caused by any subprogram and cannot be traced; the functions also cannot be tested separately because they depend on outside state. Parameters and return values make the data flow visible at the call site.

Common mistake

Trap 1 — treating one correct test case as a correct program. A case that divides evenly hides the integer-division error; testing proves there is an error, not that there is none.
Trap 2 — passing an array by value to a sorting procedure. The copy is sorted then thrown away; the original array is unchanged with no error reported.
Trap 3 — blaming the algorithm when the precondition is violated. Binary search on an unsorted array is the caller's fault.

Key takeaway

Lesson 4 wrap-up. Four things to take into the exam room. One, a precondition is what the caller must guarantee, a postcondition is what the subprogram guarantees. Two, a value is a copy, a reference is the original; sorting needs a reference. Three, normal, boundary, invalid plus the empty case and the one-element case, writing the expected result before running. Four, shrink, trace, first differing row, then rerun all the old cases.

← Two-Dimensional Arrays, Nested Loops and String Processing · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Recursion, Stacks, Queues and Linked Lists →