Introduction to Debugging Tutorial
Why Learn About Debugging?
Learn a basic debugging technique in this tutorial that will help you fix your program or script.
Experienced, professional programmers use this technique. You should, too.
I wrote this programming tutorial because many people send me code that does not work and ask me what is wrong with it and to fix it.
Other people are frustrated at not being able to get a program or script to work. Programming can be frustrating and
challenging. Every programmer faces code that does not work. Basic debugging skills will help you alot.
The examples in this tutorial are written in PHP. Every scripting language has an
equivalent. Change the syntax to your preferred language.
Debug Using Print Statements
Your friend is the helpful print statement. Make your program tell you what it is doing.
Lesson 1: Debugging Problems With Variables
A common situation: the value of your variable is not being set, or is not what you expect. Print
the value in your browser. Add code like this to your program:
<?php
print "the value of myVariable is: " . $myVariable . "<br>";
?>
If the value of myVariable is "Hello World!" a helpful message appears in your
browser that says the value of myVariable is: Hello World!
If you have not successfully set your variable to anything, the message informs you by
saying nothing after the semi-colon:the value of myVariable is:
Lesson 2: Debugging Problems With What Is Being Executed
A common situation: you do not know what part of your program is executing. I had this problem
recently trying to get my XML parser to work (example page created by my XML parser
program). I had a series of nested if else statements, while statements
and for loops. I was lost and the program did not work. I added some simple print statements to isolate
what was (or was not) being executed.
Add something like:
<?php
print "now going to execute the function on line 242 <br>";
?>
<?php
print "completed executing the function on line 242<br>";
?>
Lesson 3: Remember To Remove Your Print Statements
Remember to take out your print statements when you upload your program. You can set a variable that
acts as a flag for whether you are in debug mode or not. If in debug mode, then execute your
handly print statements. Otherwise, ignore them. I will provide that syntax another day.
Summary for Basic Debugging Using Print Statements
Use print statments in your code to make your program tell you what the program is trying to
do, or failing to do. You are the only one who will see your print statements. Do not spend time making them fancy.
Learn this technique and you are on your way to becoming an experienced programmer.
|