Java Reference
In-Depth Information
System.out.println("You have $" + money + " left.");
System.out.print("Cash is in good shape. Bet liberally.");
System.out.print("How much do you want to bet? ");
bet = console.nextInt();
}
This construct is repetitious and can be made more efficient by using a technique
called factoring . Using this simple technique, you factor out common pieces of code
from the different branches of the if/else construct. In the preceding program,
three different branches can execute, depending on the value of the variable money .
Start by writing down the series of actions being performed in each branch and com-
paring them, as in Figure 4.6.
Depending upon money
Money < 500
500 < Money < 1000
Money > 1000
Report money
Warn about low money
Prompt for bet
Read bet
Report money
Report okay money
Prompt for bet
Read bet
Report money
Report good money
Prompt for bet
Read bet
Figure 4.6 if/else branches before factoring
You can factor at both the top and the bottom of a construct like this. If you notice
that the top statement in each branch is the same, you factor it out of the branching part
and put it before the branch. Similarly, if the bottom statement in each branch is the
same, you factor it out of the branching part and put it after the loop. You can factor the
top statement in each of these branches and the bottom two statements, as in Figure 4.7.
Report money
Depending upon money
Money < 500
500 < Money < 1000
Money > 1000
Warn about low money
Report okay money
Report good money
Prompt for bet
Read bet
Figure 4.7 if/else branches after factoring
Thus, the preceding code can be reduced to the following more succinct version:
System.out.println("You have $" + money + " left.");
if (money < 500) {
 
Search WWH ::




Custom Search