Java Reference
In-Depth Information
7.7.3
Verbal walkthroughs
Another way in which the walkthrough technique can be used to find errors in a program is to try
explaining to another person what a class or method does. This works in two completely different ways:
The person you explain the code to might spot the error for you.
You will often find that the simple act of trying to put into words what a piece of code should
do is enough to trigger in your own mind an understanding of why it does not.
This latter effect is so common that it can often be worth explaining a piece of code to someone who
is completely unfamiliar with it—not in anticipation that they will find the error, but that you will!
7.8
Print statements
Probably the most common technique used to understand and debug programs—even amongst
experienced programmers—is to annotate methods temporarily with print statements. Print
statements are popular because they exist in most languages, they are available to everyone,
and they are very easy to add with any editor. No additional software or language features are
required to make use of them. As a program runs, these additional print statements will typi-
cally provide a user with information such as:
which methods have been called
the values of parameters
the order in which methods have been called
the values of local variables and fields at strategic points
Code 7.5 shows an example of how the numberPressed method might look with print state-
ments added. Such information is particularly helpful in providing a picture of the way in which
the state of an object changes as mutators are called. To help support this, it is often worth
including a debugging method that prints out the current values of all the fields of an object.
Code 7.6 shows such a reportState method for the CalcEngine class.
Code 7.5
A method with debug-
ging print statements
added
/**
* A number button was pressed.
* @param number The number that was pressed.
*/
public void numberPressed( int number)
{
System.out.println( "numberPressed called with: " +
number);
displayValue = displayValue * 10 + number;
System.out.println( "displayValue is: " + displayValue +
" at end of numberPressed." );
}
 
 
Search WWH ::




Custom Search