Finding Bugs


Now that we understand the different kinds of bugs and have looked at some of the most common syntax problems in JavaScript, let’s move on to look at some techniques for finding bugs.

You’ve already seen how the syntax error message displays work in Internet Explorer and Netscape. I won’t go over that ground again. But sometimes it’s useful to create your own error messages to use for diagnostic purposes. These error messages can also display the value of variables at specific times. This can be particularly helpful in pinpointing logical errors.

I’ll show you two techniques for displaying error messages that include the values of variables, and then I’ll move on to a discussion of program testing.

Ad-Hoc Error Displays

The lowly alert statement can be your biggest ally in debugging a program. I find that I insert alert statements or their analog in other development environments, such as the MessageBox.Show method in Visual Basic .NET, even when sophisticated debugging tools are available.

It can be helpful to generate ad-hoc displays of variables and their values if you suspect that something is wrong. This technique is particularly useful within loops; alert statements are most often used.

Using alert Statements

You can use alert statements to display variable values in a spontaneous fashion. In other words, this is a debugging tool that’s easy to implement (and requires no special software). The only downsides are that the alert statement only provides the information you program it to display and that you may have to click OK many times to cycle through a loop. (An alert box is modal, meaning that you can’t move on until you’ve clicked OK.)

Let’s work through an example. You probably remember the code used in Chapter 9, “ Manipulating Strings,” used to count the words in a string (this was shown in Listing 9-5). Listing 10-2 shows this code again.

Listing 10.2: Counting Words in a String (Okay Version)

start example
 function countWords(str){     var count = 0;     var words = str.split(" ");      for (var i=0 ; i < words.length ; i++){         // inner loop -- do the count         if (words[i] != "")            count += 1;      }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  } 
end example

Now let’s intentionally mutilate the countWords function shown in Listing 10-1 so that the loop malfunctions by introducing a one-off error. If we start the loop at one rather than zero by using the iteration statement:

 for (var i=1 ; i < words.length ; i++){     ...  } 

then the countWords function will give us the wrong result. Listing 10-3 shows the “broken” version of the code.

Listing 10.3: Counting Words in a String (“Broken” Version)

start example
 function countWords(str){     var count = 0;     var words = str.split(" ");      for (var i=1 ; i < words.length ; i++){         // inner loop -- do the count         if (words[i] != "")            count += 1;      }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  } 
end example

If you run the code shown in Listing 10-3 in an appropriate user interface and enter some words separated by spaces, you’ll see that the count of words is, indeed, one off (you can count the words entered in Figure 10-7 to verify this!).

click to expand
Figure 10-7: The count of words is one less than the actual number of words entered.

Adding an alert statement that displays the value of the iteration variable and the current word will immediately pinpoint the problem. Here’s how.

To Use an alert Statement to Display Values:

  1. Within the code where you suspect a problem (for example, the function shown in Listing 10-3), place an alert statement that displays the current iteration counter value, as well as the value of any related array elements:

     alert("The count is " + i + " ; current word is " + words[i]); 

  2. Save the revised function (as shown in Listing 10-4).

    Listing 10.4: Broken Word Counting Function with Diagnostic alert Statement

    start example
     function countWords(str){     var count = 0;     var words = str.split(" ");      for (var i=1 ; i < words.length ; i++){         // inner loop -- do the count         alert("The count is " + i + " ; current word is "           + words[i]);        if (words[i] != "")           count += 1;     }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  } 
    end example

  3. Open the page containing the suspect function in a browser.

  4. Run the suspect function. An alert box will be displayed for each loop iteration, showing the value of the iteration counter variable and the value of the related words array element. The first time the alert box is displayed, as you can see in Figure 10-8, it shows you that the first word has been skipped in the count, so it’s easy to figure out that you have a one-off error and that your loop is starting higher by one than where it should start.

    click to expand
    Figure 10-8: The alert box shows that the problem is a one-off error in the loop iteration variable.

Displaying Values in a Window

Variety, as they say, is the spice of life. A simple variation on the alert box as a diagnostic tool is to display diagnostic messages in a separate window. It’s easy to write the values to a separate window, and this has the advantage of not interrupting execution of the code while the diagnostic statements are executed. You can read the list of values in one fell swoop.

If you entered a long sentence with many words in the previous example and then clicked through all the resulting alert boxes, you’ll understand why this can be a good idea.

The example uses the broken word counting loop shown earlier in Listing 10-3.

To Use a Document Window to Display Values:

  1. Add a statement that creates a new window:

     var debugMe = window.open("", "debugMe",     "height=300,width=250,resizable=yes,scrollbars=yes"); 

    This statement should come before, so that it’s processed before, the suspect function.

  2. Within the suspect function and within the loop, add a statement that displays the iteration and array value, once for each pass through the loop:

     debugMe.document.writeln("The count is " + i +     " ; current word is " + words[i] + "<BR>"); 

  3. Save the page containing the faulty function and diagnostic window statement (the code for both are shown in Listing 10-5).

    Listing 10.5: Counting Words in a String with Diagnostic Separate Window Display

    start example
     var debugMe = window.open("", "debugMe",     "height=300,width=250,resizable=yes,scrollbars=yes");  function countWords(str){     var count = 0;     var words = str.split(" ");      for (var i=1 ; i < words.length ; i++){         // inner loop -- do the count          debugMe.document.writeln("The count is " + i +              " ; current word is " + words[i] + "<BR>");         //debugMe.document.close();         if (words[i] != "")            count += 1;      }     document.theForm.results.value =        "There are " +        count +        " words in the text string you entered!";  } 
    end example

  4. Open the page in a browser and click Count Words. The function runs normally. While it’s running, the separate window is populated in each pass through the loop with the counter value and the value of the corresponding word as shown in Figure 10-9. Looking at the display in the diagnostic window shown in Figure 10-9, it’s easy to see that the first word has been omitted, leading to the natural diagnosis that the faulty function starts its count one too high!

    click to expand
    Figure 10-9: You can use a separate diagnostic window to review values without interrupting program execution.

“Real” Debugging Tools

Although ad-hoc debugging techniques come in handy even in the most advanced development environments, you should know that when you “graduate” to programming in a professional development environment you’ll have many tools available to help you with pinpointing logical errors.

In addition to essentially real-time syntax error checking, most modern development environments provide tools that provide the ability to do the following:

  • Step through code statement by statement

  • View the value of variables at any point

  • Set program breakpoints so that program execution stops at a given statement

  • Run statements interactively

  • Modify the value of variables in a running program

  • Check to see whether an assertion (a logical condition) is true or false while a program is running

  • And much, much, more.

Testing a Program

No program is complete until it has been tested. Even the simplest programs require some ad-hoc testing: Does the program run? Does it work right with some sample inputs?

With very short, simple programs you may be able to get away with informal testing. But the more complex (and longer) your program, the more need there is for rigorous testing.

Formal testing plans require a good bit of thought about the data (or inputs) you’ll use.

Even if you don’t think you need a formal testing plan, keep the following suggestions in mind when you test your programs:

  • Make sure you can “backtrack,” meaning retrace your steps, when correcting syntax problems.

  • Don’t make a problem worse when you’re attempting to fix it.

  • Beware of introducing new bugs, sometimes called side effects, when fixing the first bug.

  • Rigor and discipline in the testing process are good things. You should write down the tests you’re performing so that you know what you did and can run the same tests again if you need to do so.

  • Be diligent in attempting to “break” your application. In real life, everything that can go wrong will. Be relentless in trying to reproduce this truism in your testing process. It’s much, much better that something should break during your testing process, when you can easily fix it, than after you’ve released your program.

  • Track your testing process carefully, possibly using software designed for the testing process. Pay particular attention to the test values of variables.

  • Consider bounding values (those at the upper and lower ends of the possible ranges that can be assigned to variables).

  • One-off errors are a great source of problems, particularly in looping. You should suspect a one-off error in the loop counter whenever a logical error occurs and a loop is present.

  • Test for runtime errors under as great a variety of operating conditions as possible.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net