Java Reference
In-Depth Information
EXAMPLE: (continued)
An even better solution is to declare a boolean variable to control the do-while
loop. Inside the body of the loop we can set this variable to false when the loop
should exit. This technique has the benefit of making the code logic easier to follow,
especially if we pick a meaningful name for the variable. In the following example it is
easy to see that the loop repeats if invalidKey is true :
boolean invalidKey;
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next( );
s = s.toLowerCase( );
c = s.charAt(0);
if (c == 'a')
invalidKey = false;
else if (c == 'b')
invalidKey = false;
else
invalidKey = true;
}
while (invalidKey);
Preventive Coding
The best way to make debugging easier is to make no mistakes in the first place.
Although this is unrealistic for programs of any complexity, there are some techniques
we can use to eliminate or reduce the number of bugs in a program.
Incremental development is the technique of writing a small amount of code and
testing it before moving on and writing more code. The test may require some new code,
or a “test harness,” that won't be part of your final program but exercises your code in
some way to see if it is working. This technique makes debugging easier because if the
test fails then the error is likely in the small section of the new code that was just written.
When an error is made, be sure to learn from your mistake so you don't make it
again in the future. Did the mistake occur because of sloppy programming? Was there
some aspect of the program's design that you didn't understand or left off before writ-
ing the code? Was there something you could have done to find the error more quickly
or prevent it from happening at all? Are there other errors in your program similar to
the one you just fixed? A critical review of your coding and debugging techniques
should become a learning experience so you don't repeat your mistakes.
Finally, show your code to other programmers. Another developer might be able to
immediately spot an error in your code and eliminate a lengthy debugging process. Many
software development organizations have a formal process called code review that involves
the inspection of code by other programmers. Such reviews have the additional benefit that
incremental
development
code review
Search WWH ::




Custom Search