Page 162 -
P. 162
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 float years = daysActive / (float) 365.25;
14 float compoundInterest = principal * (float) Math.exp( rate * years );
15 return ( compoundInterest – principal );
16 }
17
18 public boolean isPremium( ) {
19 if (accountType == Account.PREMIUM || accountType == Account.PREMIUM_PLUS)
20 return true;
21 else
22 return false;
23 }
24 }
25
26 float calculateFee(Account accounts[]) {
27 float totalFee = 0;
28 Account account;
29 for (int i = 0; i < accounts.length; i++) {
30 account = accounts[i];
31 if ( account.isPremium( ) ) {
32 totalFee += BROKER_FEE_PERCENT * account.interestEarned( );
33 }
34 }
35 return totalFee;
36 }
37
38 static final double BROKER_FEE_PERCENT = 0.0125;
After these four refactorings, the inspection team agreed that the new version of this code
was much easier to understand, even though it was almost 50% longer.
The code after refactoring must behave in exactly the same way it did beforehand. In gen-
eral, every refactoring should be combined with an automated test to verify that the
behavior of the software has not changed, because it is very easy to inject defects during
refactoring. A framework of automated unit tests can ensure that the code behavior
remains intact. Luckily, the team already had a set of unit tests. They had to add tests to
verify the new Account.isPremium method, but the new code passed all of the other unit
tests and the new version of the code was checked in (along with the new tests).
Refactoring Pays for Itself
Many people are initially uncomfortable with the idea of having programmers do tasks
that don’t change the behavior of the code. But, like time spent on project planning and
software requirements engineering, the time spent refactoring is more than recouped over
the course of the project. In fact, refactoring can help a team recover code that was previ-
ously written off as an unmaintainable mess, and can also help to keep new code from
ever getting to that state.
154 CHAPTER SEVEN