Java Reference
In-Depth Information
Evaluating the boolean expression of the assert statement does take time.
Use it for simple tests, like the ones shown. But do not include in the boolean
expression a call to a function that processes every element of a large array
unless it is a temporary measure.
14.5
Debugging
Suppose a test case has detected a bug. It is now time to find the bug. This can
be a time-consuming, difficult task, like finding a needle in a haystack.
There are two ways to proceed. First, one can use a debugger —your IDE
probably has one. Second, one can sprinkle the program with print statements
and assert statements that help you track down the error.
The use of a debugger can make the task easier because it has tools that help
you analyze the program. You can step through execution of the program one
statement at a time, you can look at the values of variables and expressions as
execution proceeds, you can see what methods have been called, and so on.
But if a debugger is not available, or you do not know how to use it, you
must resort to sprinkling the program with print and assert statements. We
describe this process here.
Tracking down a bug
Suppose we are testing a program that includes the method of Fig. 14.4. In
one place "nine hundred nine " is printed on the Java console, and we can tell it
is wrong. We have to debug the program.
The bug might be either in a calculation or in a method that tranforms an
integer to its English equivalent, like anglicize . We decide to test method
anglicize . The first order of business is to:
Debugging maxim 1. Place print statements at the beginning and
end of the method (to check whether its precondition is met and
to check whether the value returned is correct).
In our case, the two statements to insert are:
System.out.println( " Start anglicize, n = " + n);
System.out.println( " End anglicize, ans = " + s);
/** = name of n, for 10 <= n <= 19 */
public static String teenName( int n)
/** = name of 10*n, for 2 <= n <= 9 */
public static String tensName( int n)
/** = name of n, for 0<n<10 , or "" if n=0 */
public static String digitName( int n)
Figure 14.6:
Specifications of some methods used in anglicizing
Search WWH ::




Custom Search