-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.4_ReplaceTempWithQuery.ts
More file actions
53 lines (45 loc) · 1008 Bytes
/
Copy path7.4_ReplaceTempWithQuery.ts
File metadata and controls
53 lines (45 loc) · 1008 Bytes
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
/**
* 以查询取代临时变量
*
* 体会:
* 1. 将一个个概念体抽离成对应函数后,整个代码达到了最高的清晰度。
*/
/**
* 初始代码
*/
class _Order {
private _quantity;
private _item;
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
const basePrice = this._quantity * this._item.price;
let discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
}
/**
* 重构后,代码达到了更高的清晰度
*/
class Order {
private _quantity;
private _item;
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
return this.basePrice * this.discountFactor;
}
get basePrice() {
return this._quantity * this._item.price;
}
get discountFactor() {
let discountFactor = 0.98;
if (this.basePrice > 1000) discountFactor -= 0.03;
return discountFactor;
}
}