Page 159 -
P. 159
9 public static final int PREMIUM = 2;
10 public static final int PREMIUM_PLUS = 3;
11 }
12
13 float calculateFee(Account accounts[]) {
14 float totalFee = 0;
15 Account account;
16 for (int i = 0; i < accounts.length; i++) {
17 account = accounts[i];
18 if ( account.accountType == Account.PREMIUM ||
19 account.accountType == Account.PREMIUM_PLUS ) {
20 totalFee += .0125 * ( account.principal
21 * Math.exp( account.rate * (account.daysActive/365.25) )
22 - account.principal );
23 }
24 }
25 return totalFee;
26 }
At first, the code seemed reasonably well designed. But as the inspection team discussed it,
a few problems emerged. One of the inspectors was not clear about the purpose of the cal-
culation that was being performed on lines 20 to 22. The programmer explained that this
was a compound interest calculation to figure out how much interest was earned on the
account, and suggested that they use the Extract Method refactoring to clarify it. They per-
formed the refactoring right there during the code review. Since this calculation only used
data that was available in the Account class, they moved it into that class, adding a new
method called interestEarned (in lines 12 to 15 below):
1 class Account {
2 float principal;
3 float rate;
4 int daysActive;
5 int accountType;
6
7 public static final int STANDARD = 0;
8 public static final int BUDGET = 1;
9 public static final int PREMIUM = 2;
10 public static final int PREMIUM_PLUS = 3;
11
12 float interestEarned( ) {
13 return ( principal * (float) Math.exp( rate * (daysActive / 365.25 ) ) )
14 - principal;
15 }
16 }
17
18 float calculateFee(Account accounts[]) {
19 float totalFee = 0;
20 Account account;
21 for (int i = 0; i < accounts.length; i++) {
22 account = accounts[i];
23 if ( account.accountType == Account.PREMIUM ||
24 account.accountType == Account.PREMIUM_PLUS )
25 totalFee += .0125 * account.interestEarned( );
26 }
27 return totalFee;
28 }
DESIGN AND PROGRAMMING 151