Java Reference
In-Depth Information
Code 7.6
A state-reporting
method
/**
* Print the values of this object's fields.
* @param where Where this state occurs.
*/
public
void
reportState(String where)
{
System.out.println(
"displayValue: "
+ displayValue +
" leftOperand: "
+ leftOperand +
" previousOperator: "
+
previousOperator +
" at "
+ where);
}
If each method of
CalcEngine
contained a print statement at its entry point and a call to
reportState
at its end, Figure 7.8 shows the output that might result from a call to the tester's
testPlus
method. (This was generated from a version of the calculator engine that can be
found in the
calculator-engine-print
project.) Such output allows us to build up a picture of how
control flows between different methods. For instance, we can see from the order in which the
state values are reported that a call to
plus
contains a nested call to
applyPreviousOperator
.
Figure 7.8
Debugging output
from a call to
testPlus
clear called
displayValue: 0 leftOperand: 0 previousOperator: at end of clear
numberPressed called with: 3
displayValue: 3 leftOperand: 0 previousOperator: at end of number...
plus called
applyPreviousOperator called
displayValue: 3 leftOperand: 3 previousOperator: at end of apply...
displayValue: 0 leftOperand: 3 previousOperator: + at end of plus
numberPressed called with: 4
displayValue: 4 leftOperand: 3 previousOperator: + at end of number...
equals called
displayValue: 7 leftOperand: 0 previousOperator: + at end of equals
Print statements can be very effective in helping us understand programs or locate errors, but
there are a number of disadvantages:
■
It is not usually practical to add print statements to every method in a class. So they are only
fully effective if the right methods have been annotated.
■
Adding too many print statements can lead to information overload. A large amount of out-
put can make it difficult to identify what you need to see. Print statements inside loops are a
particular source of this problem.
■
Once their purpose has been served, it can be tedious to remove them.
■
There is also the chance that, having removed them, they will be needed again later. It can be
very frustrating to have to put them back in again!
Search WWH ::
Custom Search