Page 160 -
P. 160
An inspector then asked what the number .0125 in line 25 was, and if it could ever change
in the future. It turned out that each broker earned a commission fee that was equal to 1.
25% of the interest earned on the account. They used the Replace Magic Number with
Symbolic Constant refactoring, replacing it with the constant BROKER_FEE_PERCENT and defining
that constant later in line 31 (and adding a leading zero to help people read the code
quickly):
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 += BROKER_FEE_PERCENT * account.interestEarned( );
26 }
27 }
28 return totalFee;
29 }
30
31 static final double BROKER_FEE_PERCENT = 0.0125;
The next issue that was raised in the code review was confusion about why the
accountType variable was being checked in lines 23 and 24. There were several account
types, and it wasn’t clear why the account was being checked for just these two types. The
programmer explained that the brokers only earn a fee for premium accounts, which
could either be of the type PREMIUM or PREMIUM_PLUS.
By using the Decompose Conditional refactoring, they were able to clarify the purpose of this
code. Adding the isPremium function to the Account class (lines 17 to 22) made it more obvi-
ous that this was a check to verify whether the account was a premium account:
1 class Account {
2 float principal;
3 float rate;
4 int daysActive;
5 int accountType;
6
152 CHAPTER SEVEN