2.7 Debugging code
When we have code that has correct syntax and runs,
but does not behave correctly, we say that there is
a bug in our code. The process of fixing our code so that
it does what we want it to is called debugging the code.
It is usually the case that debugging code takes much longer
than writing the code in the first place, so it is an important
skill to acquire.
The source of common bugs varies enormously with different computer
languages, but there are some common steps we should take when
fixing any sort of code:
- Do not blame the computer.
- There are two possible sources
of problems: our code is wrong or the computer (or software used
to run our code) is wrong. It will almost always be the case that
our code is wrong. If we are completely convinced that our code
is correct and the computer is wrong, we should go home, have a sleep and come
back the next day. The problem in our code will usually then become
apparent.
- Recheck the syntax.
- Whenever a change is made to the code,
check the syntax again before trying to run the code again. If the
syntax is wrong, there is no hope that the code will run correctly.
- Develop code incrementally.
- Do not try to write an entire web page
at once. Write a small piece of code and get that to work, then add
more code and get that to work. When things stop working, it will be
obvious which bit of code is broken.
- Apply the scientific method.
- Do not make many changes to the code
at once to
try to fix it. Even if the problem is cured, it will be difficult to
determine which change made the difference. A common problem is
introducing new problems as part of a fix for an old problem.
Make one change to the code and see
if that corrects the behaviour, then revert that change before trying
something else.
- Read the documentation.
- For all of the computer languages
that we will deal with in this book, there are official
documents plus many tutorials and online forums that contain
information and examples for writing code. Find them and read them.
- Ask for help.
- In addition to the copious manuals and tutorials
on the web, there are many forums for asking questions about
computer languages. The friendliness of theses forums varies and
it is important to read the documentation before taking this step.
Paul Murrell
This document is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.