-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathREADME.md
3803 lines (1975 loc) · 63.3 KB
/
README.md
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TypeScript 代码整洁之道
[中文](https://github.com/pipiliang/clean-code-typescript) | [English](https://github.com/labs42io/clean-code-typescript)
>将 Clean Code 的概念适用到 TypeScript,灵感来自 [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript)。
## 目录
1. [简介](#简介)
2. [变量](#变量)
3. [函数](#函数)
4. [对象与数据结构](#对象和数据结构)
5. [类](#类)
6. [SOLID原则](#SOLID原则)
7. [测试](#测试)
8. [并发](#并发)
9. [错误处理](#错误处理)
10. [格式化](#格式化)
11. [注释](#注释)
## 简介

这不是一份 TypeScript 编码风格规范,而是将 Robert C. Martin 的软件工程著作 [《Clean Code》](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) 适用到 TypeScript,引导读者使用 TypeScript 编写[易读、复用和可扩展](https://github.com/ryanmcdermott/3rs-of-software-architecture)的软件。
实际上,并不是每一个原则都要严格遵守,能被广泛认同的原则就更少了。这看起来虽然只是一份指导原则,但却是 *Clean Code* 作者对多年编程经验的凝练。
软件工程技术已有50多年的历史了,我们仍然要学习很多的东西。当软件架构和架构本身一样古老的时候,也许我们需要遵守更严格的规则。但是现在,让这些指导原则作为评估您和您的团队代码质量的试金石。
另外,理解这些原则不会立即让您变的优秀,也不意味着不会犯错。每一段代码都是从不完美开始的,通过反复走查不断趋于完美,就像黏土制作成陶艺一样,享受这个过程吧!
**[↑ 回到顶部](#目录)**
## 变量
>计算机科学只存在两个难题:缓存失效和命名。—— Phil KarIton
### 使用有意义的变量名
做有意义的区分,让读者更容易理解变量的含义。
**:-1: 反例:**
```ts
function between<T>(a1: T, a2: T, a3: T) {
return a2 <= a1 && a1 <= a3;
}
```
**:+1: 正例:**
```ts
function between<T>(value: T, left: T, right: T) {
return left <= value && value <= right;
}
```
**[↑ 回到顶部](#目录)**
### 可读的变量名
如果你不能正确读出它,那么你在讨论它时听起来就会像个白痴。
**:-1: 反例:**
```ts
class DtaRcrd102 {
private genymdhms: Date; # // 你能读出这个变量名么?
private modymdhms: Date;
private pszqint = '102';
}
```
**:+1: 正例:**
```ts
class Customer {
private generationTimestamp: Date;
private modificationTimestamp: Date;
private recordId = '102';
}
```
**[↑ 回到顶部](#目录)**
### 合并功能一致的变量
**:-1: 反例:**
```ts
function getUserInfo(): User;
function getUserDetails(): User;
function getUserData(): User;
```
**:+1: 正例:**
```ts
function getUser(): User;
```
**[↑ 回到顶部](#目录)**
### 便于搜索的名字
往往我们读代码要比写的多,所以易读性和可搜索非常重要。如果不抽取并命名有意义的变量名,那就坑了读代码的人。代码一定要便于搜索,[TSLint](https://palantir.github.io/tslint/rules/no-magic-numbers/) 就可以帮助识别未命名的常量。
**:-1: 反例:**
```ts
//86400000 代表什么?
setTimeout(restart, 86400000);
```
**:+1: 正例:**
```ts
// 声明为常量,要大写且有明确含义。
const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;
setTimeout(restart, MILLISECONDS_IN_A_DAY);
```
**[↑ 回到顶部](#目录)**
### 使用自解释的变量名
**:-1: 反例:**
```ts
declare const users:Map<string, User>;
for (const keyValue of users) {
// ...
}
```
**:+1: 正例:**
```ts
declare const users:Map<string, User>;
for (const [id, user] of users) {
// ...
}
```
**[↑ 回到顶部](#目录)**
### 避免思维映射
不要让人去猜测或想象变量的含义,*明确是王道。*
**:-1: 反例:**
```ts
const u = getUser();
const s = getSubscription();
const t = charge(u, s);
```
**:+1: 正例:**
```ts
const user = getUser();
const subscription = getSubscription();
const transaction = charge(user, subscription);
```
**[↑ 回到顶部](#目录)**
### 不添加无用的上下文
如果类名或对象名已经表达了某些信息,在内部变量名中不要再重复表达。
**:-1: 反例:**
```ts
type Car = {
carMake: string;
carModel: string;
carColor: string;
}
function print(car: Car): void {
console.log(`${this.carMake} ${this.carModel} (${this.carColor})`);
}
```
**:+1: 正例:**
```ts
type Car = {
make: string;
model: string;
color: string;
}
function print(car: Car): void {
console.log(`${this.make} ${this.model} (${this.color})`);
}
```
**[↑ 回到顶部](#目录)**
### 使用默认参数,而非短路或条件判断
通常,默认参数比短路更整洁。
**:-1: 反例:**
```ts
function loadPages(count: number) {
const loadCount = count !== undefined ? count : 10;
// ...
}
```
**:+1: 正例:**
```ts
function loadPages(count: number = 10) {
// ...
}
```
**[↑ 回到顶部](#目录)**
## 函数
### 参数越少越好 (理想情况不超过2个)
限制参数个数,这样函数测试会更容易。超过三个参数会导致测试复杂度激增,需要测试众多不同参数的组合场景。
理想情况,只有一两个参数。如果有两个以上的参数,那么您的函数可能就太过复杂了。
如果需要很多参数,请您考虑使用对象。为了使函数的属性更清晰,可以使用[解构](https://basarat.gitbooks.io/typescript/docs/destructuring.html),它有以下优点:
1. 当有人查看函数签名时,会立即清楚使用了哪些属性。
2. 解构对传递给函数的参数对象做深拷贝,这可预防副作用。(注意:**不会克隆**从参数对象中解构的对象和数组)
3. TypeScript 会对未使用的属性显示警告。
**:-1: 反例:**
```ts
function createMenu(title: string, body: string, buttonText: string, cancellable: boolean) {
// ...
}
createMenu('Foo', 'Bar', 'Baz', true);
```
**:+1: 正例:**
```ts
function createMenu(options: {title: string, body: string, buttonText: string, cancellable: boolean}) {
// ...
}
createMenu(
{
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
}
);
```
通过 TypeScript 的[类型别名](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases),可以进一步提高可读性。
```ts
type MenuOptions = {title: string, body: string, buttonText: string, cancellable: boolean};
function createMenu(options: MenuOptions) {
// ...
}
createMenu(
{
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
}
);
```
**[↑ 回到顶部](#目录)**
### 只做一件事
这是目前软件工程中最重要的规则。如果函数做不止一件事,它就更难组合、测试以及理解。反之,函数只有一个行为,它就更易于重构、代码就更清晰。如果能做好这一点,你一定很优秀!
**:-1: 反例:**
```ts
function emailClients(clients: Client[]) {
clients.forEach((client) => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
```
**:+1: 正例:**
```ts
function emailClients(clients: Client[]) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client: Client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
```
**[↑ 回到顶部](#目录)**
### 名副其实
通过函数名就可以看得出函数实现的功能。
**:-1: 反例:**
```ts
function addToDate(date: Date, month: number): Date {
// ...
}
const date = new Date();
// 从函数名很难看的出需要加什么?
addToDate(date, 1);
```
**:+1: 正例:**
```ts
function addMonthToDate(date: Date, month: number): Date {
// ...
}
const date = new Date();
addMonthToDate(date, 1);
```
**[↑ 回到顶部](#目录)**
### 每个函数只包含同一个层级的抽象
当有多个抽象级别时,函数应该是做太多事了。拆分函数以便可复用,也让测试更容易。
**:-1: 反例:**
```ts
function parseCode(code:string) {
const REGEXES = [ /* ... */ ];
const statements = code.split(' ');
const tokens = [];
REGEXES.forEach((regex) => {
statements.forEach((statement) => {
// ...
});
});
const ast = [];
tokens.forEach((token) => {
// lex...
});
ast.forEach((node) => {
// 解析 ...
});
}
```
**:+1: 正例:**
```ts
const REGEXES = [ /* ... */ ];
function parseCode(code:string) {
const tokens = tokenize(code);
const syntaxTree = parse(tokens);
syntaxTree.forEach((node) => {
// parse...
});
}
function tokenize(code: string):Token[] {
const statements = code.split(' ');
const tokens:Token[] = [];
REGEXES.forEach((regex) => {
statements.forEach((statement) => {
tokens.push( /* ... */ );
});
});
return tokens;
}
function parse(tokens: Token[]): SyntaxTree {
const syntaxTree:SyntaxTree[] = [];
tokens.forEach((token) => {
syntaxTree.push( /* ... */ );
});
return syntaxTree;
}
```
**[↑ 回到顶部](#目录)**
### 删除重复代码
重复乃万恶之源!重复意味着如果要修改某个逻辑,需要修改多处代码:cry:。
想象一下,如果你经营一家餐厅,要记录你的库存:所有的西红柿、洋葱、大蒜、香料等等。如果要维护多个库存列表,那是多么痛苦的事!
存在重复代码,是因为有两个或两个以上很近似的功能,只有一点不同,但是这点不同迫使你用多个独立的函数来做很多几乎相同的事情。删除重复代码,则意味着创建一个抽象,该抽象仅用一个函数/模块/类就可以处理这组不同的东西。
合理的抽象至关重要,这就是为什么您应该遵循[SOLID原则](#SOLID原则)。糟糕的抽象可能还不如重复代码,所以要小心!话虽如此,还是要做好抽象!尽量不要重复。
**:-1: 反例:**
```ts
function showDeveloperList(developers: Developer[]) {
developers.forEach((developer) => {
const expectedSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const githubLink = developer.getGithubLink();
const data = {
expectedSalary,
experience,
githubLink
};
render(data);
});
}
function showManagerList(managers: Manager[]) {
managers.forEach((manager) => {
const expectedSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const portfolio = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio
};
render(data);
});
}
```
**:+1: 正例:**
```ts
class Developer {
// ...
getExtraDetails() {
return {
githubLink: this.githubLink,
}
}
}
class Manager {
// ...
getExtraDetails() {
return {
portfolio: this.portfolio,
}
}
}
function showEmployeeList(employee: Developer | Manager) {
employee.forEach((employee) => {
const expectedSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const extra = employee.getExtraDetails();
const data = {
expectedSalary,
experience,
extra,
};
render(data);
});
}
```
有时,在重复代码和引入不必要的抽象而增加的复杂性之间,需要做权衡。当来自不同领域的两个不同模块,它们的实现看起来相似,复制也是可以接受的,并且比抽取公共代码要好一点。因为抽取公共代码会导致两个模块产生间接的依赖关系。
**[↑ 回到顶部](#目录)**
### 使用`Object.assign`或`解构`来设置默认对象
**:-1: 反例:**
```ts
type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
function createMenu(config: MenuConfig) {
config.title = config.title || 'Foo';
config.body = config.body || 'Bar';
config.buttonText = config.buttonText || 'Baz';
config.cancellable = config.cancellable !== undefined ? config.cancellable : true;
}
const menuConfig = {
title: null,
body: 'Bar',
buttonText: null,
cancellable: true
};
createMenu(menuConfig);
```
**:+1: 正例:**
```ts
type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
function createMenu(config: MenuConfig) {
const menuConfig = Object.assign({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
}, config);
}
createMenu({ body: 'Bar' });
```
或者,您可以使用默认值的解构:
```ts
type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
function createMenu({title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true}: MenuConfig) {
// ...
}
createMenu({ body: 'Bar' });
```
为了避免副作用,不允许显式传递`undefined`或`null`值。参见 TypeScript 编译器的`--strictnullcheck`选项。
**[↑ 回到顶部](#目录)**
### 不要使用Flag参数
Flag参数告诉用户这个函数做了不止一件事。如果函数使用布尔值实现不同的代码逻辑路径,则考虑将其拆分。
**:-1: 反例:**
```ts
function createFile(name:string, temp:boolean) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
```
**:+1: 正例:**
```ts
function createFile(name:string) {
fs.create(name);
}
function createTempFile(name:string) {
fs.create(`./temp/${name}`);
}
```
**[↑ 回到顶部](#目录)**
### 避免副作用 (part1)
当函数产生除了“一个输入一个输出”之外的行为时,称该函数产生了副作用。比如写文件、修改全局变量或将你的钱全转给了一个陌生人等。
在某些情况下,程序需要一些副作用。如先前例子中的写文件,这时应该将这些功能集中在一起,不要用多个函数/类修改某个文件。用且只用一个 service 完成这一需求。
重点是要规避常见陷阱,比如,在无结构对象之间共享状态、使用可变数据类型,以及不确定副作用发生的位置。如果你能做到这点,你才可能笑到最后!
**:-1: 反例:**
```ts
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
let name = 'Robert C. Martin';
function toBase64() {
name = btoa(name);
}
toBase64(); // produces side effects to `name` variable
console.log(name); // expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg=='
```
**:+1: 正例:**
```ts
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
const name = 'Robert C. Martin';
function toBase64(text:string):string {
return btoa(text);
}
const encodedName = toBase64(name);
console.log(name);
```
**[↑ 回到顶部](#目录)**
### 避免副作用 (part2)
在 JavaScript 中,原类型是值传递,对象、数组是引用传递。
有这样一种情况,如果您的函数修改了购物车数组,用来添加购买的商品,那么其他使用该`cart`数组的函数都将受此添加操作的影响。想象一个糟糕的情况:
用户点击“购买”按钮,该按钮调用`purchase`函数,函数请求网络并将`cart`数组发送到服务器。由于网络连接不好,购买功能必须不断重试请求。恰巧在网络请求开始前,用户不小心点击了某个不想要的项目上的“Add to Cart”按钮,该怎么办?而此时网络请求开始,那么`purchase`函数将发送意外添加的项,因为它引用了一个购物车数组,`addItemToCart`函数修改了该数组,添加了不需要的项。
一个很好的解决方案是`addItemToCart`总是克隆`cart`,编辑它,并返回克隆。这确保引用购物车的其他函数不会受到任何更改的影响。
注意两点:
1. 在某些情况下,可能确实想要修改输入对象,这种情况非常少见。且大多数可以重构,确保没副作用!(见[纯函数](https://en.wikipedia.org/wiki/Pure_function))
2. 性能方面,克隆大对象代价确实比较大。还好有一些很好的库,它提供了一些高效快速的方法,且不像手动克隆对象和数组那样占用大量内存。
**:-1: 反例:**
```ts
function addItemToCart(cart: CartItem[], item:Item):void {
cart.push({ item, date: Date.now() });
};
```
**:+1: 正例:**
```ts
function addItemToCart(cart: CartItem[], item:Item):CartItem[] {
return [...cart, { item, date: Date.now() }];
};
```
**[↑ 回到顶部](#目录)**
### 不要写全局函数
在 JavaScript 中污染全局的做法非常糟糕,这可能导致和其他库冲突,而调用你的 API 的用户在实际环境中得到一个 exception 前对这一情况是一无所知的。
考虑这样一个例子:如果想要扩展 JavaScript 的 `Array`,使其拥有一个可以显示两个数组之间差异的 `diff`方法,该怎么做呢?可以将新函数写入`Array.prototype` ,但它可能与另一个尝试做同样事情的库冲突。如果另一个库只是使用`diff`来查找数组的第一个元素和最后一个元素之间的区别呢?
更好的做法是扩展`Array`,实现对应的函数功能。
**:-1: 反例:**
```ts
declare global {
interface Array<T> {
diff(other: T[]): Array<T>;
}
}
if (!Array.prototype.diff){
Array.prototype.diff = function <T>(other: T[]): T[] {
const hash = new Set(other);
return this.filter(elem => !hash.has(elem));
};
}
```
**:+1: 正例:**
```ts
class MyArray<T> extends Array<T> {
diff(other: T[]): T[] {
const hash = new Set(other);
return this.filter(elem => !hash.has(elem));
};
}
```
**[↑ 回到顶部](#目录)**
### 函数式编程优于命令式编程
尽量使用函数式编程!
**:-1: 反例:**
```ts
const contributions = [
{
name: 'Uncle Bobby',
linesOfCode: 500
}, {
name: 'Suzie Q',
linesOfCode: 1500
}, {
name: 'Jimmy Gosling',
linesOfCode: 150
}, {
name: 'Gracie Hopper',
linesOfCode: 1000
}
];
let totalOutput = 0;