Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 10: Debugging and testing
Debugging modular programs
Writing highly abstracted and modular programs actually helps make it easier for you to debug your program.
In addition to being self-explanatory, your functions also act as natural ‘breakpoints’ for you to debug your codes.
If you have structured your program well, then you will find it easier to debug as your program is mainly written in terms of ‘inputs’ and ‘outputs’ to/from function calls.
So, if your program is not working as expected, you can start by first figuring out whether the problem is with your input to a function or with your output returned by a function.
For example, you might find that the value of average_dist
is not as expected.
1 2 3 4 5 |
|
So you can first check whether dist1
and dist2
is correct.
1 2 3 4 5 6 7 |
|
If both dist1
and dist2
are correct, it means that there is something wrong with how you subsequently used these values, i.e. at average_dist = dist1 + dist2 / 2
. Indeed, in this example, it should be average_dist = (dist1+dist2) / 2
because of operator precedence.
Otherwise, you should then check whether it is the input to the function that is the problem. You might spot in this example that you have provided the wrong input to the last parameter of the function call in Line 2 (should be y1_right
and not y2_right
).
1 2 3 4 5 |
|
Another way to check the input is to actually print out values inside the function definition itself, before you do anything else (Lines 4-7). You can also print out the return value here (Line 12, before you return the value). This way, you only need to do it only once, rather than for every function call as earlier. Of course, this also depends on which is more convenient for your situation)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Here, if the input is correct and the output is wrong, then there is clearly a problem with the function itself, so you can focus your attention on debugging inside the function definition.
The more you program and the more you debug, the more experience you will gain, and the more your debugging skills with subsequently improve.