-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11.1_SeparateQueryFromModifier.ts
More file actions
71 lines (63 loc) · 1.28 KB
/
11.1_SeparateQueryFromModifier.ts
File metadata and controls
71 lines (63 loc) · 1.28 KB
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
/**
* 将查询函数和修改函数分离
*
* Separate Query from Modifier
*
* 规则:任何有返回值的函数,都不应该有看得到的副作用(尽量遵守,但不能绝对遵守)
*
* 明确表现出“有副作用”和“无副作用”两种函数的差异,是一个很好的想法
*
*/
/**
* 重构前
*
* @returns
*/
function getTotalOutstandingAndSendBill() {
const result = customer.invoices.reduce(
(total, each) => each.amount + total,
0
);
sendBill();
return result;
}
/**
* 重构后
*
* 第一个属于查询函数,第二个属于修改函数
*
* 函数分离后,函数更加符合职责单一原则
*
* @returns
*/
function totalOutstanding() {
return customer.invoices.reduce((total, each) => each.amount + total, 0);
}
function sendBill() {
emailGateway.send(formatBill(customer));
}
/**
* ------------- 以下是准备数据 -------------
*/
function formatBill(_customer) {
return JSON.stringify(_customer);
}
const emailGateway = {
send: (str: string) => {
console.log(str);
},
};
const customer = {
invoices: [
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
{ amount: 3 },
],
};