-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract_method.js
118 lines (64 loc) · 2.13 KB
/
extract_method.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Somewhere in a function...
if (user.currentAddress.state == 'NY' || (user.permanantAddress.state == 'NY' && !user.notVacationing)) {
deposit = 5;
}
// Extracting that conditional logic into a method
function currentlyInNewYork(user) {
return (user.currentAddress.state == 'NY' || (user.permanantAddress.state == 'NY' && !user.notVacationing));
}
// ...improves readability and understanding
if (currentlyInNewYork(user)) {
deposit = 5;
}
// ...and also structure, say it lived in here
function determineRecyclingDeposit(user) {
if (user.currentAddress.state == 'NY' || (user.permanantAddress.state == 'NY' && !user.notVacationing)) {
return 5;
}
else if (user.currentAddress.state == 'AL' || (user.permanantAddress.state == 'AL' && !user.notVacation)) {
return 0;
}
else if (user.currentAddress.state == 'MI' || (user.permanantAddress.state == 'MI' && !user.notVacation)) {
return 10;
}
//... and on and on
}
//Step 1. Extract method, a bit different this time
// (or even reuse our first function if we needed)
function currentlyInState(stateCode, user) {
return (user.currentAddress.state == stateCode || (user.permanantAddress.state == 'NY' && !user.notVacationing))
}
// Note that currentlyInNewYork is just a special case
function currentlyInNewYork(user) {
return currentlyInState('NY', user)
}
function determineRecyclingDeposit(user) {
if (currentlyInState('NY', user)) {
return 5;
}
else if (currentlyInNewYork('AL', user)) {
return 0;
}
else if (currentlyInNewYork('MI', user)) {
return 10;
}
//... so on
}
// So we can even make the function nicer...
function determineRecyclingDeposit(user) {
const depositMaps = {
'MI': 10,
'NY': 5,
'AL': 0
// ... and on and on
};
_.each((stateCode, deposit) => {
if (currentlyInState(stateCode, user)) {
return deposit;
}
});
}
// And now we are looking at the problem differently:
// ...should we really looping through all the states each time?
// ...can't we somehow just get the user's state and look it up?
// These questions were there before, but harder to see!