-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathParameterizeMethod.java
48 lines (41 loc) · 1.15 KB
/
ParameterizeMethod.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package ch10;
/*
* Several methods do similar things but with different values contained in the method body
*
* Create one method that uses a parameter for the different values
*/
class Employee {
public void tenPercentRaise() {
salary *= 1.1;
}
public void fivePercentRaise() {
salary *= 1.05;
}
protected Dollars baseCharge() {
double result = Math.min(lastUsage(), 100) * 0.03;
if (lastUsage() > 100) {
result += (Math.min(lastUsage(), 200) - 100) * 0.05;
}
if (lastUsage() > 200) {
result += (lastUsage() - 200) * 0.07;
}
return new Dollars(result);
}
}
class EmployeeRefactored {
public void raise(double factor) {
salary *= (1 + factor);
}
// repetitive on the basis of a few values that can be passed in as parameters
protected Dollars baseCharge() {
double result = usageInRange(0, 100) * 0.03;
result += usageInRange(100, 200) * 0.05;
result += usageInRange(200, Integer.MAX_VALUE) * 0.07;
return new Dollars(result);
}
protected int usageInRange(int start, int end) {
if (lastUsage() > start)
return Math.min(lastUsage(), end) - start;
return 0;
}
}