├── .gitattributes ├── .github └── FUNDING.yml ├── LICENSE ├── README.md └── _config.yml /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-documentation=false 2 | *.md linguist-language=TypeScript -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ['paypal.me/beginor'] 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 Labs42 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 代码整洁的 TypeScript [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Clean%20Code%20Typescript&url=https://github.com/labs42io/clean-code-typescript) 2 | 3 | > 原文链接 [clean-code-typescript](https://github.com/labs42io/clean-code-typescript) 4 | 5 | 将代码整洁的理念适配至 TypeScript , 灵感来自于[代码整洁的 JavaScript ](https://github.com/ryanmcdermott/clean-code-javascript)。 6 | 7 | ## 目录 8 | 9 | 1. [简介](#简介) 10 | 2. [变量](#变量) 11 | 3. [函数](#函数) 12 | 4. [对象和数据结构](#对象和数据结构) 13 | 5. [类](#类) 14 | 6. [SOLID](#solid) 15 | 7. [测试](#测试) 16 | 8. [并发](#并发) 17 | 9. [错误处理](#错误处理) 18 | 10. [格式化](#格式化) 19 | 11. [注释](#注释) 20 | 12. [翻译](#翻译) 21 | 22 | ## 简介 23 | 24 | ![一张用你阅读代码时吐槽的数量来评估软件质量的搞笑图片](https://www.osnews.com/images/comics/wtfm.jpg) 25 | 26 | 将源自 Robert C. Martin 的 [*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) 27 | 的软件工程原则适配到 TypeScript 。 这不是一个代码风格指南, 它是一个使用 TypeScript 来生产 28 | 可读的, 可重用的, 以及可重构的软件的指南。 29 | 30 | 这里的每一项原则都不是必须遵守的, 甚至只有更少的能够被广泛认可。 这些仅仅是指南而已, 但是却是 31 | *Clean Code* 作者多年经验的结晶。 32 | 33 | 我们的软件工程行业只有短短的 50 年, 依然有很多要我们去学习。 当软件架构与建筑架构一样古老时, 34 | 也许我们将会有硬性的规则去遵守。 而现在, 让这些指南做为你和你的团队生产的 TypeScript 代码的 35 | 质量的标准。 36 | 37 | 还有一件事: 知道这些指南并不能马上让你成为一个更加出色的软件开发者, 并且使用它们工作多年也并 38 | 不意味着你不再会犯错误。 每一段代码最开始都是草稿, 像湿粘土一样被打造成最终的形态。 最后当我们 39 | 和搭档们一起审查代码时清除那些不完善之处, 不要因为最初需要改善的草稿代码而自责, 而是对那些代 40 | 码下手。 41 | 42 | **[⬆ 返回目录](#目录)** 43 | 44 | ## 变量 45 | 46 | ### 使用有意义的变量名称 47 | 48 | 使用可以区分的名称, 让读者知道他们的区别是什么。 49 | 50 | **不好的:** 51 | 52 | ```ts 53 | function between(a1: T, a2: T, a3: T): boolean { 54 | return a2 <= a1 && a1 <= a3; 55 | } 56 | 57 | ``` 58 | 59 | **好的:** 60 | 61 | ```ts 62 | function between(value: T, left: T, right: T): boolean { 63 | return left <= value && value <= right; 64 | } 65 | ``` 66 | 67 | **[⬆ 返回目录](#目录)** 68 | 69 | ### 使用可拼读的变量名称 70 | 71 | 如果你不能把它读出来, 那你就不能和同事讨论它, 这看起来像块纱布。 72 | 73 | **不好的:** 74 | 75 | ```ts 76 | type DtaRcrd102 = { 77 | genymdhms: Date; 78 | modymdhms: Date; 79 | pszqint: number; 80 | } 81 | ``` 82 | 83 | **好的:** 84 | 85 | ```ts 86 | type Customer = { 87 | generationTimestamp: Date; 88 | modificationTimestamp: Date; 89 | recordId: number; 90 | } 91 | ``` 92 | 93 | **[⬆ 返回目录](#目录)** 94 | 95 | ### 为相同类型的变量使用相同的词汇 96 | 97 | **不好的:** 98 | 99 | ```ts 100 | function getUserInfo(): User; 101 | function getUserDetails(): User; 102 | function getUserData(): User; 103 | ``` 104 | 105 | **好的:** 106 | 107 | ```ts 108 | function getUser(): User; 109 | ``` 110 | 111 | **[⬆ 返回目录](#目录)** 112 | 113 | ### 使用可搜索的名称 114 | 115 | 我们要阅读的代码比要写的代码多得多, 所以我们写出的代码的可读性和可搜索性是很重要的。 使用没有 116 | 意义的变量名将会导致我们的程序难于理解, 将会伤害我们的读者, 所以请使用可搜索的变量名。 类似 [TSLint](https://palantir.github.io/tslint/rules/no-magic-numbers/) 117 | 的工具可以帮助我们找到未命名的常量。 118 | 119 | **不好的:** 120 | 121 | ```ts 122 | // What the heck is 86400000 for? 123 | // 艹, 86400000 是什么鬼? 124 | setTimeout(restart, 86400000); 125 | ``` 126 | 127 | **好的:** 128 | 129 | ```ts 130 | // Declare them as capitalized named constants. 131 | // 将他们声明为大写的变量 132 | const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000; 133 | 134 | setTimeout(restart, MILLISECONDS_IN_A_DAY); 135 | ``` 136 | 137 | **[⬆ 返回目录](#目录)** 138 | 139 | ### 使用解释性的变量 140 | 141 | **不好的:** 142 | 143 | ```ts 144 | declare const users: Map; 145 | 146 | for (const keyValue of users) { 147 | // iterate through users map 148 | } 149 | ``` 150 | 151 | **好的:** 152 | 153 | ```ts 154 | declare const users: Map; 155 | 156 | for (const [id, user] of users) { 157 | // iterate through users map 158 | } 159 | ``` 160 | 161 | **[⬆ 返回目录](#目录)** 162 | 163 | ### 避免心理映射 164 | 165 | 显示比隐式更好。 *清晰为王!* 166 | 167 | **不好的:** 168 | 169 | ```ts 170 | const u = getUser(); 171 | const s = getSubscription(); 172 | const t = charge(u, s); 173 | ``` 174 | 175 | **好的:** 176 | 177 | ```ts 178 | const user = getUser(); 179 | const subscription = getSubscription(); 180 | const transaction = charge(user, subscription); 181 | ``` 182 | 183 | **[⬆ 返回目录](#目录)** 184 | 185 | ### 不添加不必要的上下文 186 | 187 | 如果你的类/类型/对象名有意义, 不必在变量名上再重复。 188 | 189 | **不好的:** 190 | 191 | ```ts 192 | type Car = { 193 | carMake: string; 194 | carModel: string; 195 | carColor: string; 196 | } 197 | 198 | function print(car: Car): void { 199 | console.log(`${car.carMake} ${car.carModel} (${car.carColor})`); 200 | } 201 | ``` 202 | 203 | **好的:** 204 | 205 | ```ts 206 | type Car = { 207 | make: string; 208 | model: string; 209 | color: string; 210 | } 211 | 212 | function print(car: Car): void { 213 | console.log(`${car.make} ${car.model} (${car.color})`); 214 | } 215 | ``` 216 | 217 | **[⬆ 返回目录](#目录)** 218 | 219 | ### 使用默认变量替代短路运算或条件 220 | 221 | 默认参数通常比短路运算更清晰。 222 | 223 | **不好的:** 224 | 225 | ```ts 226 | function loadPages(count?: number) { 227 | const loadCount = count !== undefined ? count : 10; 228 | // ... 229 | } 230 | ``` 231 | 232 | **好的:** 233 | 234 | ```ts 235 | function loadPages(count: number = 10) { 236 | // ... 237 | } 238 | ``` 239 | 240 | **[⬆ 返回目录](#目录)** 241 | 242 | ## 函数 243 | 244 | ### 函数参数 (两个以下最理想) 245 | 246 | 限制函数参数的个数是非常重要的, 因为这样将使你的函数容易进行测试。 一旦超过三个参数将会导致组 247 | 合爆炸, 因为你不得不编写大量针对每个参数的测试用例。 248 | 249 | 一个或者两个参数是理想状况, 如果可能的话, 三个参数的情况应该避免, 超过三个应该被重构。 通常, 250 | 如果你有一个超过两个函数的参数, 那就意味着你的函数尝试做太多的事情。 如果不是, 多数情况下一个 251 | 更高级对象可能会满足需求。 252 | 253 | 当你发现你自己需要大量的参数时, 考虑使用一个对象。 254 | 255 | 为了让函数需要的属性更明显, 可以使用[解构](https://basarat.gitbooks.io/typescript/docs/destructuring.html)语法。 它有三个优点: 256 | 257 | 1. 当有人查看函数签名时, 会立刻清楚用到了哪些属性。 258 | 259 | 2. 解构还克隆传递给函数的参数对象的指定原始值。 这有助于预防副作用。 注意:不会克隆参数对象中解构的对象和数组。 260 | 261 | 3. TypeScript 会警告您未使用的属性,如果没有解构,这将是不可能的。 262 | 263 | **不好的:** 264 | 265 | ```ts 266 | function createMenu(title: string, body: string, buttonText: string, cancellable: boolean) { 267 | // ... 268 | } 269 | 270 | createMenu('Foo', 'Bar', 'Baz', true); 271 | ``` 272 | 273 | **好的:** 274 | 275 | ```ts 276 | function createMenu(options: { title: string, body: string, buttonText: string, cancellable: boolean }) { 277 | // ... 278 | } 279 | 280 | createMenu({ 281 | title: 'Foo', 282 | body: 'Bar', 283 | buttonText: 'Baz', 284 | cancellable: true 285 | }); 286 | ``` 287 | 288 | 你可以通过[类型别名](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases)来显著提高可读性: 289 | 290 | ```ts 291 | 292 | type MenuOptions = { title: string, body: string, buttonText: string, cancellable: boolean }; 293 | 294 | function createMenu(options: MenuOptions) { 295 | // ... 296 | } 297 | 298 | createMenu({ 299 | title: 'Foo', 300 | body: 'Bar', 301 | buttonText: 'Baz', 302 | cancellable: true 303 | }); 304 | ``` 305 | 306 | **[⬆ 返回目录](#目录)** 307 | 308 | ### 函数应当只做一件事情 309 | 310 | 这是软件工程中最重要的一条规则, 当函数需要做更多的事情时, 它们将会更难进行编写、 测试和推理。 311 | 当你能将一个函数隔离到只有一个动作, 他们将能够被容易的进行重构并且你的代码将会更容易阅读。 如 312 | 果你严格遵守本指南中的这一条, 你将会领先于许多开发者。 313 | 314 | **不好的:** 315 | 316 | ```ts 317 | function emailClients(clients: Client) { 318 | clients.forEach((client) => { 319 | const clientRecord = database.lookup(client); 320 | if (clientRecord.isActive()) { 321 | email(client); 322 | } 323 | }); 324 | } 325 | ``` 326 | 327 | **好的:** 328 | 329 | ```ts 330 | function emailClients(clients: Client) { 331 | clients.filter(isActiveClient).forEach(email); 332 | } 333 | 334 | function isActiveClient(client: Client) { 335 | const clientRecord = database.lookup(client); 336 | return clientRecord.isActive(); 337 | } 338 | ``` 339 | 340 | **[⬆ 返回目录](#目录)** 341 | 342 | ### 函数名称应该说明它要做什么 343 | 344 | **不好的:** 345 | 346 | ```ts 347 | function addToDate(date: Date, month: number): Date { 348 | // ... 349 | } 350 | 351 | const date = new Date(); 352 | 353 | // It's hard to tell from the function name what is added 354 | // 很难从函数名看出加了什么 355 | addToDate(date, 1); 356 | ``` 357 | 358 | **好的:** 359 | 360 | ```ts 361 | function addMonthToDate(date: Date, month: number): Date { 362 | // ... 363 | } 364 | 365 | const date = new Date(); 366 | addMonthToDate(date, 1); 367 | ``` 368 | 369 | **[⬆ 返回目录](#目录)** 370 | 371 | ### 函数应该只有一个抽象级别 372 | 373 | 当在你的函数中有多于一个抽象级别时, 你的函数通常做了太多事情。 拆分函数将会提升重用性和测试性。 374 | 375 | **不好的:** 376 | 377 | ```ts 378 | function parseCode(code: string) { 379 | const REGEXES = [ /* ... */ ]; 380 | const statements = code.split(' '); 381 | const tokens = []; 382 | 383 | REGEXES.forEach((regex) => { 384 | statements.forEach((statement) => { 385 | // ... 386 | }); 387 | }); 388 | 389 | const ast = []; 390 | tokens.forEach((token) => { 391 | // lex... 392 | }); 393 | 394 | ast.forEach((node) => { 395 | // parse... 396 | }); 397 | } 398 | ``` 399 | 400 | **好的:** 401 | 402 | ```ts 403 | const REGEXES = [ /* ... */ ]; 404 | 405 | function parseCode(code: string) { 406 | const tokens = tokenize(code); 407 | const syntaxTree = parse(tokens); 408 | 409 | syntaxTree.forEach((node) => { 410 | // parse... 411 | }); 412 | } 413 | 414 | function tokenize(code: string): Token[] { 415 | const statements = code.split(' '); 416 | const tokens: Token[] = []; 417 | 418 | REGEXES.forEach((regex) => { 419 | statements.forEach((statement) => { 420 | tokens.push( /* ... */ ); 421 | }); 422 | }); 423 | 424 | return tokens; 425 | } 426 | 427 | function parse(tokens: Token[]): SyntaxTree { 428 | const syntaxTree: SyntaxTree[] = []; 429 | tokens.forEach((token) => { 430 | syntaxTree.push( /* ... */ ); 431 | }); 432 | 433 | return syntaxTree; 434 | } 435 | ``` 436 | 437 | **[⬆ 返回目录](#目录)** 438 | 439 | ### 移除冗余代码 440 | 441 | 竭尽你的全力去避免冗余代码。 冗余代码是不好的, 因为它意味着当你需要修改一些逻辑时会有多个地方 442 | 需要修改。 443 | 444 | 想象一下你在经营一家餐馆, 你需要记录所有的库存西红柿, 洋葱, 大蒜, 各种香料等等。 如果你有多 445 | 个记录列表, 当你用西红柿做一道菜时你得更新多个列表。 如果你只有一个列表, 就只有一个地方需要更 446 | 新! 447 | 448 | 你有冗余代码通常是因为你有两个或多个稍微不同的东西, 它们共享大部分, 但是它们的不同之处迫使你使 449 | 用两个或更多独立的函数来处理大部分相同的东西。 移除冗余代码意味着创建一个可以处理这些不同之处的 450 | 抽象的函数/模块/类。 451 | 452 | 让这个抽象正确是关键的, 这是为什么要你遵循 *Classes* 那一章的 SOLID 的原因。 不好的抽象比冗 453 | 余代码更差, 所以要谨慎行事。 既然已经这么说了, 如果你能够做出一个好的抽象, 才去做。 不要重复 454 | 你自己, 否则你会发现当你要修改一个东西时时刻需要修改多个地方。 455 | 456 | **不好的:** 457 | 458 | ```ts 459 | function showDeveloperList(developers: Developer[]) { 460 | developers.forEach((developer) => { 461 | const expectedSalary = developer.calculateExpectedSalary(); 462 | const experience = developer.getExperience(); 463 | const githubLink = developer.getGithubLink(); 464 | 465 | const data = { 466 | expectedSalary, 467 | experience, 468 | githubLink 469 | }; 470 | 471 | render(data); 472 | }); 473 | } 474 | 475 | function showManagerList(managers: Manager[]) { 476 | managers.forEach((manager) => { 477 | const expectedSalary = manager.calculateExpectedSalary(); 478 | const experience = manager.getExperience(); 479 | const portfolio = manager.getMBAProjects(); 480 | 481 | const data = { 482 | expectedSalary, 483 | experience, 484 | portfolio 485 | }; 486 | 487 | render(data); 488 | }); 489 | } 490 | ``` 491 | 492 | **好的:** 493 | 494 | ```ts 495 | class Developer { 496 | // ... 497 | getExtraDetails() { 498 | return { 499 | githubLink: this.githubLink, 500 | } 501 | } 502 | } 503 | 504 | class Manager { 505 | // ... 506 | getExtraDetails() { 507 | return { 508 | portfolio: this.portfolio, 509 | } 510 | } 511 | } 512 | 513 | function showEmployeeList(employee: Developer | Manager) { 514 | employee.forEach((employee) => { 515 | const expectedSalary = employee.calculateExpectedSalary(); 516 | const experience = employee.getExperience(); 517 | const extra = employee.getExtraDetails(); 518 | 519 | const data = { 520 | expectedSalary, 521 | experience, 522 | extra, 523 | }; 524 | 525 | render(data); 526 | }); 527 | } 528 | ``` 529 | 530 | 您应该对代码冗余持批判的态度。 有时需要在冗余代码和通过因不必要的抽象而增加的复杂性之间做权衡。 当来自两个不同模块的两个实现看起来相似但存在于不同的域中时,冗余(可能)是可接受的并且优于提取公共代码。 在这种情况下,提取的公共代码引入了两个模块之间的间接依赖关系。 531 | 532 | **[⬆ 返回目录](#目录)** 533 | 534 | ### 使用 Object.assign 设置默认对象或者解构 535 | 536 | **不好的:** 537 | 538 | ```ts 539 | type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; 540 | 541 | function createMenu(config: MenuConfig) { 542 | config.title = config.title || 'Foo'; 543 | config.body = config.body || 'Bar'; 544 | config.buttonText = config.buttonText || 'Baz'; 545 | config.cancellable = config.cancellable !== undefined ? config.cancellable : true; 546 | 547 | // ... 548 | } 549 | 550 | createMenu({ body: 'Bar' }); 551 | ``` 552 | 553 | **好的:** 554 | 555 | ```ts 556 | type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; 557 | 558 | function createMenu(config: MenuConfig) { 559 | const menuConfig = Object.assign({ 560 | title: 'Foo', 561 | body: 'Bar', 562 | buttonText: 'Baz', 563 | cancellable: true 564 | }, config); 565 | 566 | // ... 567 | } 568 | 569 | createMenu({ body: 'Bar' }); 570 | ``` 571 | 572 | 另外, 也可以使用解构来处理默认值: 573 | 574 | ```ts 575 | type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; 576 | 577 | function createMenu({ title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true }: MenuConfig) { 578 | // ... 579 | } 580 | 581 | createMenu({ body: 'Bar' }); 582 | ``` 583 | 584 | 要避免显示传递 `undefined` 或者 `null` 值产生的负面影响或异常行为, 可以设置 TypeScript 编译器来禁止。 请查看 TypeScript 的 [`--strictNullChecks`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#--strictnullchecks) 选项。 585 | 586 | **[⬆ 返回目录](#目录)** 587 | 588 | ### 不要使用标记位做为函数参数 589 | 590 | 标记位是告诉你的用户这个函数做了不只一件事情。 函数应该只做一件事情。 如果你的函数因为一个布尔值 591 | 出现不同的代码路径, 请拆分它们。 592 | 593 | **不好的:** 594 | 595 | ```ts 596 | function createFile(name: string, temp: boolean) { 597 | if (temp) { 598 | fs.create(`./temp/${name}`); 599 | } else { 600 | fs.create(name); 601 | } 602 | } 603 | ``` 604 | 605 | **好的:** 606 | 607 | ```ts 608 | function createTempFile(name: string) { 609 | createFile(`./temp/${name}`); 610 | } 611 | 612 | function createFile(name: string) { 613 | fs.create(name); 614 | } 615 | ``` 616 | 617 | **[⬆ 返回目录](#目录)** 618 | 619 | ### 避免副作用(第 1 部分) 620 | 621 | 如果一个函数做了除接受一个值然后返回一个值或多个值之外的任何事情, 它将会产生副作用, 它可能是 622 | 写入一个文件, 修改一个全局变量, 或者意外的把你所有的钱连接到一个陌生人那里。 623 | 624 | 现在在你的程序中确实偶尔需要副作用, 就像上面的代码, 你也许需要写入到一个文件, 你需要做的是集 625 | 中化你要做的事情, 不要让多个函数或者类写入一个特定的文件, 用一个服务来实现它, 一个并且只有一 626 | 个。 627 | 628 | 重点是避免这些常见的易犯的错误, 比如在对象之间共享状态而不使用任何结构, 使用任何地方都可以写入 629 | 的可变的数据类型, 没有集中化导致副作用。 如果你能做到这些, 那么你将会比其它的码农大军更加幸福。 630 | 631 | **不好的:** 632 | 633 | ```ts 634 | // Global variable referenced by following function. 635 | // 全局变量被下面的函数引用 636 | let name = 'Robert C. Martin'; 637 | 638 | function toBase64() { 639 | name = btoa(name); 640 | } 641 | 642 | toBase64(); 643 | // If we had another function that used this name, now it'd be a Base64 value 644 | // 如果我们有另一个函数使用这个 name , 现在它应该是一个 Base64 字符串值。 645 | 646 | // expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg==' 647 | // 期望打印出 'Robert C. Martin' 但是却是 'Um9iZXJ0IEMuIE1hcnRpbg==' 648 | console.log(name); 649 | ``` 650 | 651 | **好的:** 652 | 653 | ```ts 654 | const name = 'Robert C. Martin'; 655 | 656 | function toBase64(text: string): string { 657 | return btoa(text); 658 | } 659 | 660 | const encodedName = toBase64(name); 661 | console.log(name); 662 | ``` 663 | 664 | **[⬆ 返回目录](#目录)** 665 | 666 | ### 避免副作用 (第 2 部分) 667 | 668 | 在 JavaScript 中, 基本类型通过值进行传递而对象/类通过引用传递。 以对象和数组为例, 如果你的函数对一个购物车数组做出了更改, 比如添加了一个要购买的东西, 那么其它使用这个购物车数组的任何函数都会受到影响。 这样貌似挺不错的, 不过也可能很糟糕。 让我们来想象一个糟糕的情况: 669 | 670 | 用户点击“购买”按钮, 调用一个 `purchase` 函数, 发出一个网络请求, 经购物车数组发送到服务器。 由于网络情况比较差, `purchase` 函数只能尝试重新发送请求。 现在, 用户在网络请求开始之前, 突然点击了“添加到购物车”按钮, 添加了一项并不是真心想买的东西, 那么 `purchase` 函数将会发送这个突然被添加的项目, 因为它们引用了同一个购物车数组对象, 而这个对象 `addItemToCart` 函数修改了, 添加了一个不想要的项目。 671 | 672 | 一个好的方案应该是让 `addItemToCart` 始终克隆一个购物车副本, 编辑并返回副本。 这样能够保证它不会被其它任何函数引用, 也就不能进行修改。 673 | 674 | 这种方案下需要注意以下 2 个问题: 675 | 676 | 1. 可能在有些情况下确实需要修改输入对象, 但是当你采用这种编程实践之后, 你会发现这种情况是寥寥无几的。 很多东西可以被重构来消除负面影响。 (参考[纯函数](https://zh.wikipedia.org/wiki/%E7%BA%AF%E5%87%BD%E6%95%B0)/[Pure function](https://en.wikipedia.org/wiki/Pure_function)) 677 | 678 | 2. 克隆大对象可能比较消耗性能。 幸运的是, 在实际操作上, 并不是一个多大的问题, 因为有优秀的类库可以让这一操作变得非常快, 同时也比手工克隆这些对象和数组节省很多内存。 679 | 680 | **不好的:** 681 | 682 | ```ts 683 | function addItemToCart(cart: CartItem[], item: Item): void { 684 | cart.push({ item, date: Date.now() }); 685 | }; 686 | ``` 687 | 688 | **好的:** 689 | 690 | ```ts 691 | function addItemToCart(cart: CartItem[], item: Item): CartItem[] { 692 | return [...cart, { item, date: Date.now() }]; 693 | }; 694 | ``` 695 | 696 | **[⬆ 返回目录](#目录)** 697 | 698 | ### 不要写入全局函数 699 | 700 | 污染全局在 JavaScript 中是一个不好的做法, 因为你可能会和另外一个类库冲突, 你的 API 的用户 701 | 可能不够聪明, 直到他们得到在生产环境得到一个异常。 让我们来考虑这样一个例子: 假设你要扩展 702 | JavaScript 的 原生 `Array` , 添加一个可以显示两个数组的不同之处的 `diff` 方法, 你可以在 703 | `Array.prototype` 中写一个新的方法, 但是它可能会和尝试做相同事情的其它类库发生冲突。 如果有 704 | 另外一个类库仅仅使用 `diff` 方法来查找数组的第一个元素和最后一个元素之间的不同之处呢? 这就是 705 | 为什么使用 ES2015/ES6 的类是一个更好的做法的原因, 只要简单的扩展全局的 `Array` 即可。 706 | 707 | **不好的:** 708 | 709 | ```ts 710 | declare global { 711 | interface Array { 712 | diff(other: T[]): Array; 713 | } 714 | } 715 | 716 | if (!Array.prototype.diff) { 717 | Array.prototype.diff = function (other: T[]): T[] { 718 | const hash = new Set(other); 719 | return this.filter(elem => !hash.has(elem)); 720 | }; 721 | } 722 | ``` 723 | 724 | **好的:** 725 | 726 | ```ts 727 | class MyArray extends Array { 728 | diff(other: T[]): T[] { 729 | const hash = new Set(other); 730 | return this.filter(elem => !hash.has(elem)); 731 | }; 732 | } 733 | ``` 734 | 735 | **[⬆ 返回目录](#目录)** 736 | 737 | ### 函数式编程优于指令式编程 738 | 739 | 当你可以使用函数式编程风格时请尽情使用。 740 | 741 | **不好的:** 742 | 743 | ```ts 744 | const contributions = [ 745 | { 746 | name: 'Uncle Bobby', 747 | linesOfCode: 500 748 | }, { 749 | name: 'Suzie Q', 750 | linesOfCode: 1500 751 | }, { 752 | name: 'Jimmy Gosling', 753 | linesOfCode: 150 754 | }, { 755 | name: 'Gracie Hopper', 756 | linesOfCode: 1000 757 | } 758 | ]; 759 | 760 | let totalOutput = 0; 761 | 762 | for (let i = 0; i < contributions.length; i++) { 763 | totalOutput += contributions[i].linesOfCode; 764 | } 765 | ``` 766 | 767 | **好的:** 768 | 769 | ```ts 770 | const contributions = [ 771 | { 772 | name: 'Uncle Bobby', 773 | linesOfCode: 500 774 | }, { 775 | name: 'Suzie Q', 776 | linesOfCode: 1500 777 | }, { 778 | name: 'Jimmy Gosling', 779 | linesOfCode: 150 780 | }, { 781 | name: 'Gracie Hopper', 782 | linesOfCode: 1000 783 | } 784 | ]; 785 | 786 | const totalOutput = contributions 787 | .reduce((totalLines, output) => totalLines + output.linesOfCode, 0); 788 | ``` 789 | 790 | **[⬆ 返回目录](#目录)** 791 | 792 | ### 封装条件语句 793 | 794 | **不好的:** 795 | 796 | ```ts 797 | if (subscription.isTrial || account.balance > 0) { 798 | // ... 799 | } 800 | ``` 801 | 802 | **好的:** 803 | 804 | ```ts 805 | function canActivateService(subscription: Subscription, account: Account) { 806 | return subscription.isTrial || account.balance > 0 807 | } 808 | 809 | if (canActivateService(subscription, account)) { 810 | // ... 811 | } 812 | ``` 813 | 814 | **[⬆ 返回目录](#目录)** 815 | 816 | ### 避免负面条件 817 | 818 | **不好的:** 819 | 820 | ```ts 821 | function isEmailNotUsed(email: string): boolean { 822 | // ... 823 | } 824 | 825 | if (isEmailNotUsed(email)) { 826 | // ... 827 | } 828 | ``` 829 | 830 | **好的:** 831 | 832 | ```ts 833 | function isEmailUsed(email): boolean { 834 | // ... 835 | } 836 | 837 | if (!isEmailUsed(node)) { 838 | // ... 839 | } 840 | ``` 841 | 842 | **[⬆ 返回目录](#目录)** 843 | 844 | ### 避免条件语句 845 | 846 | 这看起来似乎是一个不可能的任务。 第一次听到这个时, 多数人会说: “没有 `if` 语句还能期望我干 847 | 啥呢”, 答案是多数情况下你可以使用多态来完成同样的任务。 第二个问题通常是 “好了, 那么做很棒, 848 | 但是我为什么想要那样做呢”, 答案是我们学到的上一条代码整洁之道的理念: 一个函数应当只做一件事情。 849 | 当你有使用 `if` 语句的类/函数是, 你在告诉你的用户你的函数做了不止一件事情。 记住: 只做一件 850 | 事情。 851 | 852 | **不好的:** 853 | 854 | ```ts 855 | class Airplane { 856 | private type: string; 857 | // ... 858 | 859 | getCruisingAltitude() { 860 | switch (this.type) { 861 | case '777': 862 | return this.getMaxAltitude() - this.getPassengerCount(); 863 | case 'Air Force One': 864 | return this.getMaxAltitude(); 865 | case 'Cessna': 866 | return this.getMaxAltitude() - this.getFuelExpenditure(); 867 | default: 868 | throw new Error('Unknown airplane type.'); 869 | } 870 | } 871 | 872 | private getMaxAltitude(): number { 873 | // ... 874 | } 875 | } 876 | ``` 877 | 878 | **好的:** 879 | 880 | ```ts 881 | abstract class Airplane { 882 | protected getMaxAltitude(): number { 883 | // shared logic with subclasses ... 884 | } 885 | 886 | // ... 887 | } 888 | 889 | class Boeing777 extends Airplane { 890 | // ... 891 | getCruisingAltitude() { 892 | return this.getMaxAltitude() - this.getPassengerCount(); 893 | } 894 | } 895 | 896 | class AirForceOne extends Airplane { 897 | // ... 898 | getCruisingAltitude() { 899 | return this.getMaxAltitude(); 900 | } 901 | } 902 | 903 | class Cessna extends Airplane { 904 | // ... 905 | getCruisingAltitude() { 906 | return this.getMaxAltitude() - this.getFuelExpenditure(); 907 | } 908 | } 909 | ``` 910 | 911 | **[⬆ 返回目录](#目录)** 912 | 913 | ### 避免类型检查 914 | 915 | TypeScript 是 JavaScript 的一个严格语法的超急, 为这门语言增加了可选的静态类型检查。 916 | 始终倾向于给变量、 参数以及返回值定义类型一体现 TypeScript 的完整特征。 917 | 这将使重构变得更加容易。 918 | 919 | **不好的** 920 | 921 | ```ts 922 | function travelToTexas(vehicle: Bicycle | Car) { 923 | if (vehicle instanceof Bicycle) { 924 | vehicle.pedal(currentLocation, new Location('texas')); 925 | } else if (vehicle instanceof Car) { 926 | vehicle.drive(currentLocation, new Location('texas')); 927 | } 928 | } 929 | ``` 930 | 931 | **好的** 932 | 933 | ```ts 934 | type Vehicle = Bicycle | Car; 935 | 936 | function travelToTexas(vehicle: Vehicle) { 937 | vehicle.move(currentLocation, new Location('texas')); 938 | } 939 | ``` 940 | 941 | **[⬆ 返回目录](#目录)** 942 | 943 | ### 不要过度优化 944 | 945 | 现代化浏览器运行时在幕后做大量的优化, 在大多数的时间, 做优化就是在浪费你的时间。 [这些是好的 946 | 资源](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers), 用来 947 | 查看那些地方需要优化。 为这些而优化, 直到他们被修正。 948 | 949 | **不好的:** 950 | 951 | ```ts 952 | // On old browsers, each iteration with uncached `list.length` would be costly 953 | // because of `list.length` recomputation. In modern browsers, this is optimized. 954 | // 在旧的浏览器上, 每次循环 `list.length` 都没有被缓存, 会导致不必要的开销, 因为要重新计 955 | // 算 `list.length` 。 在现代化浏览器上, 这个已经被优化了。 956 | for (let i = 0, len = list.length; i < len; i++) { 957 | // ... 958 | } 959 | ``` 960 | 961 | **好的:** 962 | 963 | ```ts 964 | for (let i = 0; i < list.length; i++) { 965 | // ... 966 | } 967 | ``` 968 | 969 | **[⬆ 返回目录](#目录)** 970 | 971 | ### 移除僵尸代码 972 | 973 | 僵死代码和冗余代码同样糟糕。 没有理由在代码库中保存它。 如果它不会被调用, 就删掉它。 当你需要 974 | 它时, 它依然保存在版本历史记录中。 975 | 976 | **不好的:** 977 | 978 | ```ts 979 | function oldRequestModule(url: string) { 980 | // ... 981 | } 982 | 983 | function requestModule(url: string) { 984 | // ... 985 | } 986 | 987 | const req = requestModule; 988 | inventoryTracker('apples', req, 'www.inventory-awesome.io'); 989 | ``` 990 | 991 | **好的:** 992 | 993 | ```ts 994 | function requestModule(url: string) { 995 | // ... 996 | } 997 | 998 | const req = requestModule; 999 | inventoryTracker('apples', req, 'www.inventory-awesome.io'); 1000 | ``` 1001 | 1002 | **[⬆ 返回目录](#目录)** 1003 | 1004 | ### 使用枚举器和生成器 1005 | 1006 | 当像流一样处理数据集时, 使用生成器和枚举器。 这样做的好处是: 1007 | 1008 | - 被调用者与生成器解耦, 这样被调用者可以决定处理多少项; 1009 | - 延迟执行, 元素按流式按需处理; 1010 | - 允许为枚举模式实现进行优化; 1011 | 1012 | **不好的:** 1013 | 1014 | ```ts 1015 | function fibonacci(n: number): number[] { 1016 | if (n === 1) return [0]; 1017 | if (n === 2) return [0, 1]; 1018 | 1019 | const items: number[] = [0, 1]; 1020 | while (items.length < n) { 1021 | items.push(items[items.length - 2] + items[items.length - 1]); 1022 | } 1023 | 1024 | return items; 1025 | } 1026 | 1027 | function print(n: number) { 1028 | fibonacci(n).forEach(fib => console.log(fib)); 1029 | } 1030 | 1031 | // Print first 10 Fibonacci numbers. 1032 | print(10); 1033 | ``` 1034 | 1035 | **好的:** 1036 | 1037 | ```ts 1038 | // 生成一个无限长的斐波那契数字流, 生成器并没有保存数字数组。 1039 | function* fibonacci(): IterableIterator { 1040 | let [a, b] = [0, 1]; 1041 | 1042 | while (true) { 1043 | yield a; 1044 | [a, b] = [b, a + b]; 1045 | } 1046 | } 1047 | 1048 | function print(n: number) { 1049 | let i = 0; 1050 | for (const fib of fibonacci()) { 1051 | if (i++ === n) break; 1052 | console.log(fib); 1053 | } 1054 | } 1055 | 1056 | // Print first 10 Fibonacci numbers. 1057 | print(10); 1058 | ``` 1059 | 1060 | 一些类库可以与原生数组类似的方式使用枚举, 将 `map`, `slice`, `forEach` 等方法串联到一起。 请参考 [itiriri](https://www.npmjs.com/package/itiriri) 的高级枚举处理示例(或者 [itiriri-async](https://www.npmjs.com/package/itiriri-async) 的异步枚举处理)。 1061 | 1062 | ```ts 1063 | import itiriri from 'itiriri'; 1064 | 1065 | function* fibonacci(): IterableIterator { 1066 | let [a, b] = [0, 1]; 1067 | 1068 | while (true) { 1069 | yield a; 1070 | [a, b] = [b, a + b]; 1071 | } 1072 | } 1073 | 1074 | itiriri(fibonacci()) 1075 | .take(10) 1076 | .forEach(fib => console.log(fib)); 1077 | ``` 1078 | 1079 | **[⬆ 返回目录](#目录)** 1080 | 1081 | ## 对象和数据结构 1082 | 1083 | ### 使用 getter 和 setter 1084 | 1085 | TypeScript 支持 getter/setter 语法。 正因为如此, 使用 getters 和 setters 来访问对象上的数据比简单的在一个对象上查找属性 1086 | 要好得多。 “为什么?” 你可能会问, 好吧, 原因请看下面的列表: 1087 | 1088 | * 当你想在获取一个对象属性的背后做更多的事情时, 你不需要在代码库中查找和修改每一处访问; 1089 | * 使用 `set` 可以让添加验证变得容易; 1090 | * 封装内部实现; 1091 | * 使用 getting 和 setting 时, 容易添加日志和错误处理; 1092 | * 你可以延迟加载对象的属性, 比如说从服务器获取。 1093 | 1094 | **不好的:** 1095 | 1096 | ```ts 1097 | type BankAccount = { 1098 | balance: number; 1099 | // ... 1100 | } 1101 | 1102 | const value = 100; 1103 | const account: BankAccount = { 1104 | balance: 0, 1105 | // ... 1106 | }; 1107 | 1108 | if (value < 0) { 1109 | throw new Error('Cannot set negative balance.'); 1110 | } 1111 | 1112 | account.balance = value; 1113 | ``` 1114 | 1115 | **好的:** 1116 | 1117 | ```ts 1118 | class BankAccount { 1119 | private accountBalance: number = 0; 1120 | 1121 | get balance(): number { 1122 | return this.accountBalance; 1123 | } 1124 | 1125 | set balance(value: number) { 1126 | if (value < 0) { 1127 | throw new Error('Cannot set negative balance.'); 1128 | } 1129 | 1130 | this.accountBalance = value; 1131 | } 1132 | 1133 | // ... 1134 | } 1135 | 1136 | // 现在 `BankAccount` 封装了验证逻辑, 如果某一天需求变化了, 需要添加额外的验证规则, 我们只需要修改 `setter` 即可, 其它依赖性代码则无需修改。 1137 | const account = new BankAccount(); 1138 | account.balance = 100; 1139 | ``` 1140 | 1141 | **[⬆ 返回目录](#目录)** 1142 | 1143 | ### 让对象拥有私有的/受保护的成员 1144 | 1145 | TypeScript 支持在类成员上添加 `public` *(默认)* , `protected` 和 `private` 修饰符。 1146 | 1147 | **不好的:** 1148 | 1149 | ```ts 1150 | class Circle { 1151 | radius: number; 1152 | 1153 | constructor(radius: number) { 1154 | this.radius = radius; 1155 | } 1156 | 1157 | perimeter() { 1158 | return 2 * Math.PI * this.radius; 1159 | } 1160 | 1161 | surface() { 1162 | return Math.PI * this.radius * this.radius; 1163 | } 1164 | } 1165 | ``` 1166 | 1167 | **好的:** 1168 | 1169 | ```ts 1170 | class Circle { 1171 | constructor(private readonly radius: number) { 1172 | } 1173 | 1174 | perimeter() { 1175 | return 2 * Math.PI * this.radius; 1176 | } 1177 | 1178 | surface() { 1179 | return Math.PI * this.radius * this.radius; 1180 | } 1181 | } 1182 | ``` 1183 | 1184 | **[⬆ 返回目录](#目录)** 1185 | 1186 | ### 倾向于不可变性 1187 | 1188 | TypeScript 的类型系统允许将类/接口的某些属性标记为 *只读* 。 这允许你在一个很舒适的方式下工作(不需要考虑意外的变化)。 针对更加高级的场景, 有一个内置的 `Readonly` 类型, 它接受一个类型 `T` , 实用类型映射, 将类型 `T` 的全部属性统统标记为只读(参考 [mapped types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types))。 1189 | 1190 | **不好的:** 1191 | 1192 | ```ts 1193 | interface Config { 1194 | host: string; 1195 | port: string; 1196 | db: string; 1197 | } 1198 | ``` 1199 | 1200 | **好的:** 1201 | 1202 | ```ts 1203 | interface Config { 1204 | readonly host: string; 1205 | readonly port: string; 1206 | readonly db: string; 1207 | } 1208 | ``` 1209 | 1210 | **[⬆ 返回目录](#目录)** 1211 | 1212 | ### 类型 vs. 接口 1213 | 1214 | 当需要并集或者交集时, 实用类型。 当需要扩展或实现时, 实用接口。 然而并没有严格的规则, 哪个适合就用哪个。 若需要一个更加详细的解释, 请参考关于 TypeScript 的类型和接口之间的不同的这个[答案](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/54101543#54101543)。 1215 | 1216 | **不好的:** 1217 | 1218 | ```ts 1219 | interface EmailConfig { 1220 | // ... 1221 | } 1222 | 1223 | interface DbConfig { 1224 | // ... 1225 | } 1226 | 1227 | interface Config { 1228 | // ... 1229 | } 1230 | 1231 | //... 1232 | 1233 | type Shape = { 1234 | // ... 1235 | } 1236 | ``` 1237 | 1238 | **好的:** 1239 | 1240 | ```ts 1241 | 1242 | type EmailConfig = { 1243 | // ... 1244 | } 1245 | 1246 | type DbConfig = { 1247 | // ... 1248 | } 1249 | 1250 | type Config = EmailConfig | DbConfig; 1251 | 1252 | // ... 1253 | 1254 | interface Shape { 1255 | // ... 1256 | } 1257 | 1258 | class Circle implements Shape { 1259 | // ... 1260 | } 1261 | 1262 | class Square implements Shape { 1263 | // ... 1264 | } 1265 | ``` 1266 | 1267 | **[⬆ 返回目录](#目录)** 1268 | 1269 | ## 类 1270 | 1271 | ### 类应当小 1272 | 1273 | 类的大小由它的职责衡量。 根据 *单一职责原则* 一个类应该小。 1274 | 1275 | **不好的:** 1276 | 1277 | ```ts 1278 | class Dashboard { 1279 | getLanguage(): string { /* ... */ } 1280 | setLanguage(language: string): void { /* ... */ } 1281 | showProgress(): void { /* ... */ } 1282 | hideProgress(): void { /* ... */ } 1283 | isDirty(): boolean { /* ... */ } 1284 | disable(): void { /* ... */ } 1285 | enable(): void { /* ... */ } 1286 | addSubscription(subscription: Subscription): void { /* ... */ } 1287 | removeSubscription(subscription: Subscription): void { /* ... */ } 1288 | addUser(user: User): void { /* ... */ } 1289 | removeUser(user: User): void { /* ... */ } 1290 | goToHomePage(): void { /* ... */ } 1291 | updateProfile(details: UserDetails): void { /* ... */ } 1292 | getVersion(): string { /* ... */ } 1293 | // ... 1294 | } 1295 | 1296 | ``` 1297 | 1298 | **好的:** 1299 | 1300 | ```ts 1301 | class Dashboard { 1302 | disable(): void { /* ... */ } 1303 | enable(): void { /* ... */ } 1304 | getVersion(): string { /* ... */ } 1305 | } 1306 | 1307 | // 将其它方法移到其它类以拆分职责 1308 | // ... 1309 | ``` 1310 | 1311 | **[⬆ 返回目录](#目录)** 1312 | 1313 | ### 高内聚和低耦合 1314 | 1315 | 内聚定义了类成员彼此相关的程度。 理想情况下,每个方法都应使用类中的所有字段。 1316 | 然后我们说这个类是*最高内聚*。 实际上, 这并非总是可行, 甚至不可取。 但是你应该更喜欢高内聚。 1317 | 1318 | 耦合指的是两个类相互依赖或相互依赖的程度。 如果其中一个类中的更改不影响其它的, 则称这些类是低耦合的。 1319 | 1320 | 好的软件设计拥有 **高内聚** 和 **低耦合** 。 1321 | 1322 | **不好的:** 1323 | 1324 | ```ts 1325 | class UserManager { 1326 | // 不好的: 每一个私有变量仅仅被一组或另一组方法使用, 这很明显说明这个类在兼负多个职责。 当我仅仅需要一个服务来获取用户事务时, 还得传递另外一个 `emailSender` 的实例。 1327 | constructor( 1328 | private readonly db: Database, 1329 | private readonly emailSender: EmailSender) { 1330 | } 1331 | 1332 | async getUser(id: number): Promise { 1333 | return await db.users.findOne({ id }); 1334 | } 1335 | 1336 | async getTransactions(userId: number): Promise { 1337 | return await db.transactions.find({ userId }); 1338 | } 1339 | 1340 | async sendGreeting(): Promise { 1341 | await emailSender.send('Welcome!'); 1342 | } 1343 | 1344 | async sendNotification(text: string): Promise { 1345 | await emailSender.send(text); 1346 | } 1347 | 1348 | async sendNewsletter(): Promise { 1349 | // ... 1350 | } 1351 | } 1352 | ``` 1353 | 1354 | **好的:** 1355 | 1356 | ```ts 1357 | class UserService { 1358 | constructor(private readonly db: Database) { 1359 | } 1360 | 1361 | async getUser(id: number): Promise { 1362 | return await this.db.users.findOne({ id }); 1363 | } 1364 | 1365 | async getTransactions(userId: number): Promise { 1366 | return await this.db.transactions.find({ userId }); 1367 | } 1368 | } 1369 | 1370 | class UserNotifier { 1371 | constructor(private readonly emailSender: EmailSender) { 1372 | } 1373 | 1374 | async sendGreeting(): Promise { 1375 | await this.emailSender.send('Welcome!'); 1376 | } 1377 | 1378 | async sendNotification(text: string): Promise { 1379 | await this.emailSender.send(text); 1380 | } 1381 | 1382 | async sendNewsletter(): Promise { 1383 | // ... 1384 | } 1385 | } 1386 | ``` 1387 | 1388 | **[⬆ 返回目录](#目录)** 1389 | 1390 | ### 组合优先于继承 1391 | 1392 | 正如[*设计模式四人帮*](https://en.wikipedia.org/wiki/Design_Patterns)所述, 如果可能, 1393 | 你应该优先使用组合而不是继承。 有许多好的理由去使用继承, 也有许多好的理由去使用组合。这个格言 1394 | 的重点是, 如果你本能的观点是继承, 那么请想一下组合能否更好的为你的问题建模。 很多情况下它真的 1395 | 可以。 1396 | 1397 | 那么你也许会这样想, “我什么时候改使用继承?” 这取决于你手上的问题, 不过这儿有一个像样的列表说 1398 | 明什么时候继承比组合更好用: 1399 | 1400 | 1. 你的继承表示"是一个"的关系而不是"有一个"的关系(人类->动物 vs 用户->用户详情); 1401 | 2. 你可以重用来自基类的代码(人可以像所有动物一样行动); 1402 | 3. 你想通过基类对子类进行全局的修改(改变所有动物行动时的热量消耗); 1403 | 1404 | **不好的:** 1405 | 1406 | ```ts 1407 | class Employee { 1408 | constructor( 1409 | private readonly name: string, 1410 | private readonly email: string) { 1411 | } 1412 | 1413 | // ... 1414 | } 1415 | 1416 | // Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee 1417 | // 不好是因为雇员“有”税率数据, EmployeeTaxData 不是一个 Employee 类型。 1418 | class EmployeeTaxData extends Employee { 1419 | constructor( 1420 | name: string, 1421 | email: string, 1422 | private readonly ssn: string, 1423 | private readonly salary: number) { 1424 | super(name, email); 1425 | } 1426 | 1427 | // ... 1428 | } 1429 | ``` 1430 | 1431 | **不好的:** 1432 | 1433 | ```ts 1434 | class Employee { 1435 | private taxData: EmployeeTaxData; 1436 | 1437 | constructor( 1438 | private readonly name: string, 1439 | private readonly email: string) { 1440 | } 1441 | 1442 | setTaxData(ssn: string, salary: number): Employee { 1443 | this.taxData = new EmployeeTaxData(ssn, salary); 1444 | return this; 1445 | } 1446 | 1447 | // ... 1448 | } 1449 | 1450 | class EmployeeTaxData { 1451 | constructor( 1452 | public readonly ssn: string, 1453 | public readonly salary: number) { 1454 | } 1455 | 1456 | // ... 1457 | } 1458 | ``` 1459 | 1460 | **[⬆ 返回目录](#目录)** 1461 | 1462 | ### 使用方法链 1463 | 1464 | 这个模式在 JavaScript 中是非常有用的, 并且在许多类库使用。 它使你的代码变得富有表现力, 并减少啰嗦。 因为这个原因, 我说, 使用方法链然后再看看你的代码会变得多么简洁。 1465 | 1466 | **不好的:** 1467 | 1468 | ```ts 1469 | class QueryBuilder { 1470 | private collection: string; 1471 | private pageNumber: number = 1; 1472 | private itemsPerPage: number = 100; 1473 | private orderByFields: string[] = []; 1474 | 1475 | from(collection: string): void { 1476 | this.collection = collection; 1477 | } 1478 | 1479 | page(number: number, itemsPerPage: number = 100): void { 1480 | this.pageNumber = number; 1481 | this.itemsPerPage = itemsPerPage; 1482 | } 1483 | 1484 | orderBy(...fields: string[]): void { 1485 | this.orderByFields = fields; 1486 | } 1487 | 1488 | build(): Query { 1489 | // ... 1490 | } 1491 | } 1492 | 1493 | // ... 1494 | 1495 | const queryBuilder = new QueryBuilder(); 1496 | queryBuilder.from('users'); 1497 | queryBuilder.page(1, 100); 1498 | queryBuilder.orderBy('firstName', 'lastName'); 1499 | 1500 | const query = queryBuilder.build(); 1501 | ``` 1502 | 1503 | **好的:** 1504 | 1505 | ```ts 1506 | class QueryBuilder { 1507 | private collection: string; 1508 | private pageNumber: number = 1; 1509 | private itemsPerPage: number = 100; 1510 | private orderByFields: string[] = []; 1511 | 1512 | from(collection: string): this { 1513 | this.collection = collection; 1514 | return this; 1515 | } 1516 | 1517 | page(number: number, itemsPerPage: number = 100): this { 1518 | this.pageNumber = number; 1519 | this.itemsPerPage = itemsPerPage; 1520 | return this; 1521 | } 1522 | 1523 | orderBy(...fields: string[]): this { 1524 | this.orderByFields = fields; 1525 | return this; 1526 | } 1527 | 1528 | build(): Query { 1529 | // ... 1530 | } 1531 | } 1532 | 1533 | // ... 1534 | 1535 | const query = new QueryBuilder() 1536 | .from('users') 1537 | .page(1, 100) 1538 | .orderBy('firstName', 'lastName') 1539 | .build(); 1540 | ``` 1541 | 1542 | **[⬆ 返回目录](#目录)** 1543 | 1544 | ## SOLID 1545 | 1546 | ### 单一职责原则 (SRP) 1547 | 1548 | 正如代码整洁之道所述, “永远不要有超过一个理由来修改一个类”。 给一个类塞满许多功能, 就像你在航 1549 | 班上只能带一个行李箱一样, 这样做的问题你的类不会有理想的内聚性, 将会有太多的理由来对它进行修改。 1550 | 最小化需要修改一个类的次数时很重要的, 因为如果一个类拥有太多的功能, 一旦你修改它的一小部分, 1551 | 将会很难弄清楚会对代码库中的其它模块造成什么影响。 1552 | 1553 | **不好的:** 1554 | 1555 | ```ts 1556 | class UserSettings { 1557 | constructor(private readonly user: User) { 1558 | } 1559 | 1560 | changeSettings(settings: UserSettings) { 1561 | if (this.verifyCredentials()) { 1562 | // ... 1563 | } 1564 | } 1565 | 1566 | verifyCredentials() { 1567 | // ... 1568 | } 1569 | } 1570 | ``` 1571 | 1572 | **好的:** 1573 | 1574 | ```ts 1575 | class UserAuth { 1576 | constructor(private readonly user: User) { 1577 | } 1578 | 1579 | verifyCredentials() { 1580 | // ... 1581 | } 1582 | } 1583 | 1584 | 1585 | class UserSettings { 1586 | private readonly auth: UserAuth; 1587 | 1588 | constructor(private readonly user: User) { 1589 | this.auth = new UserAuth(user); 1590 | } 1591 | 1592 | changeSettings(settings: UserSettings) { 1593 | if (this.auth.verifyCredentials()) { 1594 | // ... 1595 | } 1596 | } 1597 | } 1598 | ``` 1599 | 1600 | **[⬆ 返回目录](#目录)** 1601 | 1602 | ### 开闭原则 (OCP) 1603 | 1604 | Bertrand Meyer 说过, “软件实体 (类, 模块, 函数等) 应该为扩展开放, 但是为修改关闭。” 这 1605 | 是什么意思呢? 这个原则基本上说明了你应该允许用户添加功能而不必修改现有的代码。 1606 | 1607 | **不好的:** 1608 | 1609 | ```ts 1610 | class AjaxAdapter extends Adapter { 1611 | constructor() { 1612 | super(); 1613 | } 1614 | 1615 | // ... 1616 | } 1617 | 1618 | class NodeAdapter extends Adapter { 1619 | constructor() { 1620 | super(); 1621 | } 1622 | 1623 | // ... 1624 | } 1625 | 1626 | class HttpRequester { 1627 | constructor(private readonly adapter: Adapter) { 1628 | } 1629 | 1630 | async fetch(url: string): Promise { 1631 | if (this.adapter instanceof AjaxAdapter) { 1632 | const response = await makeAjaxCall(url); 1633 | // transform response and return 1634 | } else if (this.adapter instanceof NodeAdapter) { 1635 | const response = await makeHttpCall(url); 1636 | // transform response and return 1637 | } 1638 | } 1639 | } 1640 | 1641 | function makeAjaxCall(url: string): Promise { 1642 | // request and return promise 1643 | } 1644 | 1645 | function makeHttpCall(url: string): Promise { 1646 | // request and return promise 1647 | } 1648 | ``` 1649 | 1650 | **好的:** 1651 | 1652 | ```ts 1653 | abstract class Adapter { 1654 | abstract async request(url: string): Promise; 1655 | 1656 | // code shared to subclasses ... 1657 | } 1658 | 1659 | class AjaxAdapter extends Adapter { 1660 | constructor() { 1661 | super(); 1662 | } 1663 | 1664 | async request(url: string): Promise{ 1665 | // request and return promise 1666 | } 1667 | 1668 | // ... 1669 | } 1670 | 1671 | class NodeAdapter extends Adapter { 1672 | constructor() { 1673 | super(); 1674 | } 1675 | 1676 | async request(url: string): Promise{ 1677 | // request and return promise 1678 | } 1679 | 1680 | // ... 1681 | } 1682 | 1683 | class HttpRequester { 1684 | constructor(private readonly adapter: Adapter) { 1685 | } 1686 | 1687 | async fetch(url: string): Promise { 1688 | const response = await this.adapter.request(url); 1689 | // transform response and return 1690 | } 1691 | } 1692 | ``` 1693 | 1694 | **[⬆ 返回目录](#目录)** 1695 | 1696 | ### 里氏代换原则 (LSP) 1697 | 1698 | 这是针对一个非常简单的里面的一个恐怖意图, 它的正式定义是: “如果 S 是 T 的一个子类型, 那么类 1699 | 型为 T 的对象可以被类型为 S 的对象替换(例如, 类型为 S 的对象可作为类型为 T 的替代品)儿不需 1700 | 要修改目标程序的期望性质 (正确性、 任务执行性等)。” 这甚至是个恐怖的定义。 1701 | 1702 | 最好的解释是, 如果你又一个基类和一个子类, 那个基类和字类可以互换而不会产生不正确的结果。 这可 1703 | 能还有有些疑惑, 让我们来看一下这个经典的正方形与矩形的例子。 从数学上说, 一个正方形是一个矩形, 1704 | 但是你用 "is-a" 的关系用继承来实现, 你将很快遇到麻烦。 1705 | 1706 | **不好的:** 1707 | 1708 | ```ts 1709 | class Rectangle { 1710 | constructor( 1711 | protected width: number = 0, 1712 | protected height: number = 0) { 1713 | 1714 | } 1715 | 1716 | setColor(color: string): this { 1717 | // ... 1718 | } 1719 | 1720 | render(area: number) { 1721 | // ... 1722 | } 1723 | 1724 | setWidth(width: number): this { 1725 | this.width = width; 1726 | return this; 1727 | } 1728 | 1729 | setHeight(height: number): this { 1730 | this.height = height; 1731 | return this; 1732 | } 1733 | 1734 | getArea(): number { 1735 | return this.width * this.height; 1736 | } 1737 | } 1738 | 1739 | class Square extends Rectangle { 1740 | setWidth(width: number): this { 1741 | this.width = width; 1742 | this.height = width; 1743 | return this; 1744 | } 1745 | 1746 | setHeight(height: number): this { 1747 | this.width = height; 1748 | this.height = height; 1749 | return this; 1750 | } 1751 | } 1752 | 1753 | function renderLargeRectangles(rectangles: Rectangle[]) { 1754 | rectangles.forEach((rectangle) => { 1755 | const area = rectangle 1756 | .setWidth(4) 1757 | .setHeight(5) 1758 | .getArea(); // BAD: Returns 25 for Square. Should be 20. 1759 | rectangle.render(area); 1760 | }); 1761 | } 1762 | 1763 | const rectangles = [new Rectangle(), new Rectangle(), new Square()]; 1764 | renderLargeRectangles(rectangles); 1765 | ``` 1766 | 1767 | **好的:** 1768 | 1769 | ```ts 1770 | abstract class Shape { 1771 | setColor(color: string): this { 1772 | // ... 1773 | } 1774 | 1775 | render(area: number) { 1776 | // ... 1777 | } 1778 | 1779 | abstract getArea(): number; 1780 | } 1781 | 1782 | class Rectangle extends Shape { 1783 | constructor( 1784 | private readonly width = 0, 1785 | private readonly height = 0) { 1786 | super(); 1787 | } 1788 | 1789 | getArea(): number { 1790 | return this.width * this.height; 1791 | } 1792 | } 1793 | 1794 | class Square extends Shape { 1795 | constructor(private readonly length: number) { 1796 | super(); 1797 | } 1798 | 1799 | getArea(): number { 1800 | return this.length * this.length; 1801 | } 1802 | } 1803 | 1804 | function renderLargeShapes(shapes: Shape[]) { 1805 | shapes.forEach((shape) => { 1806 | const area = shape.getArea(); 1807 | shape.render(area); 1808 | }); 1809 | } 1810 | 1811 | const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; 1812 | renderLargeShapes(shapes); 1813 | ``` 1814 | 1815 | **[⬆ 返回目录](#目录)** 1816 | 1817 | ### 接口隔离原则 (ISP) 1818 | 1819 | 接口隔离原则说的是 “客户端不应该强制依赖他们不需要的接口。” 这个原则与单一职责原则紧密相关。 1820 | 1821 | 它的真正含义是你应该总是设计一种抽象的方式,使用部分方法的客户端不会得到全部实现。 这还包括禁止客户端实现他们不需要的方法。 1822 | 1823 | **不好的:** 1824 | 1825 | ```ts 1826 | interface SmartPrinter { 1827 | print(); 1828 | fax(); 1829 | scan(); 1830 | } 1831 | 1832 | class AllInOnePrinter implements SmartPrinter { 1833 | print() { 1834 | // ... 1835 | } 1836 | 1837 | fax() { 1838 | // ... 1839 | } 1840 | 1841 | scan() { 1842 | // ... 1843 | } 1844 | } 1845 | 1846 | class EconomicPrinter implements SmartPrinter { 1847 | print() { 1848 | // ... 1849 | } 1850 | 1851 | fax() { 1852 | throw new Error('Fax not supported.'); 1853 | } 1854 | 1855 | scan() { 1856 | throw new Error('Scan not supported.'); 1857 | } 1858 | } 1859 | ``` 1860 | 1861 | **好的:** 1862 | 1863 | ```ts 1864 | interface Printer { 1865 | print(); 1866 | } 1867 | 1868 | interface Fax { 1869 | fax(); 1870 | } 1871 | 1872 | interface Scanner { 1873 | scan(); 1874 | } 1875 | 1876 | class AllInOnePrinter implements Printer, Fax, Scanner { 1877 | print() { 1878 | // ... 1879 | } 1880 | 1881 | fax() { 1882 | // ... 1883 | } 1884 | 1885 | scan() { 1886 | // ... 1887 | } 1888 | } 1889 | 1890 | class EconomicPrinter implements Printer { 1891 | print() { 1892 | // ... 1893 | } 1894 | } 1895 | ``` 1896 | 1897 | **[⬆ 返回目录](#目录)** 1898 | 1899 | ### 依赖反转原则 (DIP) 1900 | 1901 | 这个原则阐述了两个重要的事情: 1902 | 1903 | 1. 高级模块不应该依赖于低级模块, 两者都应该依赖与抽象; 1904 | 2. 抽象不应当依赖于具体实现, 具体实现应当依赖于抽象。 1905 | 1906 | 这个一开始会很难理解, 但是如果你使用过 Angular.js , 你应该已经看到过通过依赖注入来实现的这个原则, 虽然他们不是相同的概念, 依赖反转原则让高级模块远离低级模块的细节和创建, 可以通过 DI 来实现。 这样做的巨大益处是降低模块间的耦合。 耦合是一个非常糟糕的开发模式, 因为会导致代码难于重构。 1907 | 1908 | DIP 通常通过使用控制反转 (IoC) 容器来达到。 [InversifyJs](https://www.npmjs.com/package/inversify) 是 TypeScript 下的一个强大的 IoC 容器示例。 1909 | 1910 | **不好的:** 1911 | 1912 | ```ts 1913 | import { readFile as readFileCb } from 'fs'; 1914 | import { promisify } from 'util'; 1915 | 1916 | const readFile = promisify(readFileCb); 1917 | 1918 | type ReportData = { 1919 | // .. 1920 | } 1921 | 1922 | class XmlFormatter { 1923 | parse(content: string): T { 1924 | // Converts an XML string to an object T 1925 | } 1926 | } 1927 | 1928 | class ReportReader { 1929 | 1930 | // BAD: We have created a dependency on a specific request implementation. 1931 | // We should just have ReportReader depend on a parse method: `parse` 1932 | private readonly formatter = new XmlFormatter(); 1933 | 1934 | async read(path: string): Promise { 1935 | const text = await readFile(path, 'UTF8'); 1936 | return this.formatter.parse(text); 1937 | } 1938 | } 1939 | 1940 | // ... 1941 | const reader = new ReportReader(); 1942 | await report = await reader.read('report.xml'); 1943 | ``` 1944 | 1945 | **好的:** 1946 | 1947 | ```ts 1948 | import { readFile as readFileCb } from 'fs'; 1949 | import { promisify } from 'util'; 1950 | 1951 | const readFile = promisify(readFileCb); 1952 | 1953 | type ReportData = { 1954 | // .. 1955 | } 1956 | 1957 | interface Formatter { 1958 | parse(content: string): T; 1959 | } 1960 | 1961 | class XmlFormatter implements Formatter { 1962 | parse(content: string): T { 1963 | // Converts an XML string to an object T 1964 | } 1965 | } 1966 | 1967 | 1968 | class JsonFormatter implements Formatter { 1969 | parse(content: string): T { 1970 | // Converts a JSON string to an object T 1971 | } 1972 | } 1973 | 1974 | class ReportReader { 1975 | constructor(private readonly formatter: Formatter) { 1976 | } 1977 | 1978 | async read(path: string): Promise { 1979 | const text = await readFile(path, 'UTF8'); 1980 | return this.formatter.parse(text); 1981 | } 1982 | } 1983 | 1984 | // ... 1985 | const reader = new ReportReader(new XmlFormatter()); 1986 | await report = await reader.read('report.xml'); 1987 | 1988 | // or if we had to read a json report 1989 | const reader = new ReportReader(new JsonFormatter()); 1990 | await report = await reader.read('report.json'); 1991 | ``` 1992 | 1993 | **[⬆ 返回目录](#目录)** 1994 | 1995 | ## 测试 1996 | 1997 | 测试比发布更加重要。 如果你没有测试或者测试不够充分, 每次发布时你就不能确认没有破坏任何事情。 1998 | 测试的量由你的团队决定, 但是拥有 100% 的覆盖率(包括所有的语句和分支)是你为什么能达到高度自信 1999 | 和内心的平静。 这意味着需要一个额外的伟大的测试框架, 也需要一个好的[覆盖率工具](http://gotwarlost.github.io/istanbul/)。 2000 | 2001 | 没有理由不写测试。 这里有[大量的优秀的 JS 测试框架](http://jstherightway.org/#testing-tools), 2002 | 选一个适合你的团队的即可。 当为团队选择了测试框架之后, 接下来的目标是为生产的每一个新的功能/模 2003 | 块编写测试。 如果你倾向于测试驱动开发(TDD), 那就太棒了, 但是要点是确认你在上线任何功能或者重 2004 | 构一个现有功能之前, 达到了需要的目标覆盖率。 2005 | 2006 | ### TDD 的三大纪律 2007 | 2008 | 1. 不得写任何生产代码, 除非是修复了一个失败的单元测试; 2009 | 2. 出现任何失败, 不得继续编写任何单元测试; 编译失败也是失败; 2010 | 3. 只要有失败的单元测试, 不得继续编写任何生产代码; 2011 | 2012 | **[⬆ 返回目录](#目录)** 2013 | 2014 | ### F.I.R.S.T. 规则 2015 | 2016 | 简洁测试应当遵循的规则: 2017 | 2018 | - **快速 (Fast)** 测试应当很快, 因为我们希望经常运行他们。 2019 | 2020 | - **独立 (Independent)** 测试不应当相互依赖。 不管是单独运行还是一起以任意顺序运行, 应当有相同的输出。 2021 | 2022 | - **重复 (Repeatable)** 测试应当是在任何环境下可重复的, 测试失败不应有任何理由。 2023 | 2024 | - **自验证 (Self-Validating)** 一个测试的结果应该是 *通过* 或者 *失败* 。 不需要去比较日志文件来判断测试是否通过。 2025 | 2026 | - **及时 (Timely)** 单元测试应该在产品代码之前编写。 如果你在产品代码之后编写测试, 就会发现写测试太难了。 2027 | 2028 | **[⬆ 返回目录](#目录)** 2029 | 2030 | ### 每个测试单个概念 2031 | 2032 | 单元测试也应当遵守 *单一职责原则* 。 让每个单元测试只包含一个断言。 2033 | 2034 | **不好的:** 2035 | 2036 | ```ts 2037 | import { assert } from 'chai'; 2038 | 2039 | describe('AwesomeDate', () => { 2040 | it('handles date boundaries', () => { 2041 | let date: AwesomeDate; 2042 | 2043 | date = new AwesomeDate('1/1/2015'); 2044 | assert.equal('1/31/2015', date.addDays(30)); 2045 | 2046 | date = new AwesomeDate('2/1/2016'); 2047 | assert.equal('2/29/2016', date.addDays(28)); 2048 | 2049 | date = new AwesomeDate('2/1/2015'); 2050 | assert.equal('3/1/2015', date.addDays(28)); 2051 | }); 2052 | }); 2053 | ``` 2054 | 2055 | **好的:** 2056 | 2057 | ```ts 2058 | import { assert } from 'chai'; 2059 | 2060 | describe('AwesomeDate', () => { 2061 | it('handles 30-day months', () => { 2062 | const date = new AwesomeDate('1/1/2015'); 2063 | assert.equal('1/31/2015', date.addDays(30)); 2064 | }); 2065 | 2066 | it('handles leap year', () => { 2067 | const date = new AwesomeDate('2/1/2016'); 2068 | assert.equal('2/29/2016', date.addDays(28)); 2069 | }); 2070 | 2071 | it('handles non-leap year', () => { 2072 | const date = new AwesomeDate('2/1/2015'); 2073 | assert.equal('3/1/2015', date.addDays(28)); 2074 | }); 2075 | }); 2076 | ``` 2077 | 2078 | **[⬆ 返回目录](#目录)** 2079 | 2080 | ### 测试的名称应当揭示它的动机 2081 | 2082 | 当测试失败时, 它的名称就是错误的第一指示。 2083 | 2084 | **不好的:** 2085 | 2086 | ```ts 2087 | describe('Calendar', () => { 2088 | it('2/29/2020', () => { 2089 | // ... 2090 | }); 2091 | 2092 | it('throws', () => { 2093 | // ... 2094 | }); 2095 | }); 2096 | ``` 2097 | 2098 | **好的:** 2099 | 2100 | ```ts 2101 | describe('Calendar', () => { 2102 | it('should handle leap year', () => { 2103 | // ... 2104 | }); 2105 | 2106 | it('should throw when format is invalid', () => { 2107 | // ... 2108 | }); 2109 | }); 2110 | ``` 2111 | 2112 | **[⬆ 返回目录](#目录)** 2113 | 2114 | ## 并发 2115 | 2116 | ### 倾向于 Promise 而不是回调 2117 | 2118 | 回调不够简洁, 因为他们会产生过多的嵌套 *(回调地狱)* 。 这些工具可以将使用回调函数转换成返回 Promise 的函数 (对于 Node.js , 参考 [`util.promisify`](https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original) , 而对于更加通用的场景, 参考 [pify](https://www.npmjs.com/package/pify), [es6-promisify](https://www.npmjs.com/package/es6-promisify) )。 2119 | 2120 | **不好的:** 2121 | 2122 | ```ts 2123 | import { get } from 'request'; 2124 | import { writeFile } from 'fs'; 2125 | 2126 | function downloadPage(url: string, saveTo: string, callback: (error: Error, content?: string) => void) { 2127 | get(url, (error, response) => { 2128 | if (error) { 2129 | callback(error); 2130 | } else { 2131 | writeFile(saveTo, response.body, (error) => { 2132 | if (error) { 2133 | callback(error); 2134 | } else { 2135 | callback(null, response.body); 2136 | } 2137 | }); 2138 | } 2139 | }); 2140 | } 2141 | 2142 | downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html', (error, content) => { 2143 | if (error) { 2144 | console.error(error); 2145 | } else { 2146 | console.log(content); 2147 | } 2148 | }); 2149 | ``` 2150 | 2151 | **好的:** 2152 | 2153 | ```ts 2154 | import { get } from 'request'; 2155 | import { writeFile } from 'fs'; 2156 | import { promisify } from 'util'; 2157 | 2158 | const write = promisify(writeFile); 2159 | 2160 | function downloadPage(url: string, saveTo: string): Promise { 2161 | return get(url) 2162 | .then(response => write(saveTo, response)); 2163 | } 2164 | 2165 | downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html') 2166 | .then(content => console.log(content)) 2167 | .catch(error => console.error(error)); 2168 | ``` 2169 | 2170 | Promise 提供了一些帮助方法来让代码变得更加简洁: 2171 | 2172 | | Pattern | Description | 2173 | | ------------------------ | ----------------------------------------- | 2174 | | `Promise.resolve(value)` | 将一个值转换为一个已解决的 Promise 。 | 2175 | | `Promise.reject(error)` | 将一个错误转换为一个已拒绝的 Promise 。 | 2176 | | `Promise.all(promises)` | 从一组 Promise 返回一个新的 Promise , 如果这组 Promise 全部解决, 则解决新生成的 Promise , 否则拒绝新生成的 Promise 。 | 2177 | | `Promise.race(promises)`| 从多个 Promise 生成一个新的 Promise , 返回值由第一个解决或者拒绝的 Promise 决定。 | 2178 | 2179 | `Promise.all` 在需要并行运行任务时非常有用, 而 `Promise.race` 则可以比较容易的实现类似超时的 Promise 。 2180 | 2181 | **[⬆ 返回目录](#目录)** 2182 | 2183 | ### Async/Await 比 Promise 更加简洁 2184 | 2185 | 使用`async` /`await`语法,您可以编写更清晰,更易理解的链接承诺的代码。 通过在方法前面标记 `async` 关键字, 可以让 JavaScript 运行时在遇到 `async` 关键字时暂停(当使用 Promise 时才能这样做)。 2186 | 2187 | **不好的:** 2188 | 2189 | ```ts 2190 | import { get } from 'request'; 2191 | import { writeFile } from 'fs'; 2192 | import { promisify } from 'util'; 2193 | 2194 | const write = util.promisify(writeFile); 2195 | 2196 | function downloadPage(url: string, saveTo: string): Promise { 2197 | return get(url).then(response => write(saveTo, response)); 2198 | } 2199 | 2200 | downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html') 2201 | .then(content => console.log(content)) 2202 | .catch(error => console.error(error)); 2203 | ``` 2204 | 2205 | **Good:** 2206 | 2207 | ```ts 2208 | import { get } from 'request'; 2209 | import { writeFile } from 'fs'; 2210 | import { promisify } from 'util'; 2211 | 2212 | const write = promisify(writeFile); 2213 | 2214 | async function downloadPage(url: string, saveTo: string): Promise { 2215 | const response = await get(url); 2216 | await write(saveTo, response); 2217 | return response; 2218 | } 2219 | 2220 | // somewhere in an async function 2221 | try { 2222 | const content = await downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html'); 2223 | console.log(content); 2224 | } catch (error) { 2225 | console.error(error); 2226 | } 2227 | ``` 2228 | 2229 | **[⬆ 返回目录](#目录)** 2230 | 2231 | ## 错误处理 2232 | 2233 | 抛出错误是件好事! 他们意味着当程序出错时, 成功的通知运行时, 并通过停止执行当前堆栈上的函数, 终止进程(在 Node 中), 并且在控制台打印错误堆栈信息以通知你。 2234 | 2235 | ### 始终使用为抛出或拒绝使用错误对象 (Error) 2236 | 2237 | JavaScript 以及 TypeScript 允许你 `抛出` 任意对象, 一个 Promise 也能够用任意对象进行拒绝。 使用 `抛出 (throw)` 语法和 `错误 (Error)` 类型是非常明智的, 这是因为错误消息可能会被更高级的语句用 `cache` 捕获到。 而捕获一个字符串可能会非常令人疑惑的, 同时也会让[调试更加痛苦](https://basarat.gitbooks.io/typescript/docs/types/exceptions.html#always-use-error)。 同样的理由, 拒绝 Promise 时, 也应该使用 `Error` 类型。 2238 | 2239 | **不好的:** 2240 | 2241 | ```ts 2242 | function calculateTotal(items: Item[]): number { 2243 | throw 'Not implemented.'; 2244 | } 2245 | 2246 | function get(): Promise { 2247 | return Promise.reject('Not implemented.'); 2248 | } 2249 | ``` 2250 | 2251 | **好的:** 2252 | 2253 | ```ts 2254 | function calculateTotal(items: Item[]): number { 2255 | throw new Error('Not implemented.'); 2256 | } 2257 | 2258 | function get(): Promise { 2259 | return Promise.reject(new Error('Not implemented.')); 2260 | } 2261 | 2262 | // or equivalent to: 2263 | 2264 | async function get(): Promise { 2265 | throw new Error('Not implemented.'); 2266 | } 2267 | ``` 2268 | 2269 | 使用 `Error` 类型的好处是它被 `try/catch/finally` 支持, 并且所有的 Error 对象都有一个隐式属性 `stack` , 在调试时很有用。 还有一个选择, 那就是不使用 `throw` 语法, 始终返回自定义的错误对象。 TypeScript 下更加容易, 参看下面的例子: 2270 | 2271 | ```ts 2272 | type Result = { isError: false, value: R }; 2273 | type Failure = { isError: true, error: E }; 2274 | type Failable = Result | Failure; 2275 | 2276 | function calculateTotal(items: Item[]): Failable { 2277 | if (items.length === 0) { 2278 | return { isError: true, error: 'empty' }; 2279 | } 2280 | 2281 | // ... 2282 | return { isError: false, value: 42 }; 2283 | } 2284 | ``` 2285 | 2286 | 要查看这个主意的更详细说明, 请参考[原帖](https://medium.com/@dhruvrajvanshi/making-exceptions-type-safe-in-typescript-c4d200ee78e9)。 2287 | 2288 | **[⬆ 返回目录](#目录)** 2289 | 2290 | ### 不要忽略捕获到的错误 2291 | 2292 | 捕获到错误后,什么都不做, 既不能让你修复错误, 也不能让你响应错误。 使用 `console.log` 将错误输出到控制台并不是十分高明, 因为经常会有大量的内容被打印输出到控制台, 很难再被找到。 一旦你在 `try/catch` 中包括了任何一点儿代码, 这就意味着你认为这里可能会有错误发生, 你应当针对它有一个计划, 或者一段代码来进行处理。 2293 | 2294 | **不好的:** 2295 | 2296 | ```ts 2297 | try { 2298 | functionThatMightThrow(); 2299 | } catch (error) { 2300 | console.log(error); 2301 | } 2302 | 2303 | // or even worse 2304 | // 更糟糕的是 2305 | 2306 | try { 2307 | functionThatMightThrow(); 2308 | } catch (error) { 2309 | // ignore error 2310 | // 完全忽略错误 2311 | } 2312 | ``` 2313 | 2314 | **好的:** 2315 | 2316 | ```ts 2317 | import { logger } from './logging' 2318 | 2319 | try { 2320 | functionThatMightThrow(); 2321 | } catch (error) { 2322 | logger.log(error); 2323 | } 2324 | ``` 2325 | 2326 | **[⬆ 返回目录](#目录)** 2327 | 2328 | ### 不要忽略被拒绝的 Promise 2329 | 2330 | 由于同样的原因, 你不应该忽略由 `try/catch` 捕获到的错误。 2331 | 2332 | **不好的:** 2333 | 2334 | ```ts 2335 | getUser() 2336 | .then((user: User) => { 2337 | return sendEmail(user.email, 'Welcome!'); 2338 | }) 2339 | .catch((error) => { 2340 | console.log(error); 2341 | }); 2342 | ``` 2343 | 2344 | **好的:** 2345 | 2346 | ```ts 2347 | import { logger } from './logging' 2348 | 2349 | getUser() 2350 | .then((user: User) => { 2351 | return sendEmail(user.email, 'Welcome!'); 2352 | }) 2353 | .catch((error) => { 2354 | logger.log(error); 2355 | }); 2356 | 2357 | // 或者使用 async/await 语法: 2358 | 2359 | try { 2360 | const user = await getUser(); 2361 | await sendEmail(user.email, 'Welcome!'); 2362 | } catch (error) { 2363 | logger.log(error); 2364 | } 2365 | ``` 2366 | 2367 | **[⬆ 返回目录](#目录)** 2368 | 2369 | ## 格式化 2370 | 2371 | 格式化是主观的。 就像其它规则一样, 没有必须让你遵守的硬性规则。 重点是不要因为格式去争论, 有大量的工具来自动格式化, 使用其中的一个即可! 因为做为工程师去争论格式化就是在浪费时间和金钱。 要遵守的通用规则是 *保持一致的格式化规则* 。 2372 | 2373 | 对 TypeScript 来说, 有一个强大的工具叫做 [TSLint](https://palantir.github.io/tslint/) 。 它是一个可以显著提高代码的可读性和可维护性的静态分析工具。 也已经有一些可用的 TSLint 配置供你在项目中参考: 2374 | 2375 | - [标准的 TSLint 配置](https://www.npmjs.com/package/tslint-config-standard) - 标准风格规则 2376 | 2377 | - [Airbnb 的 TSLint 配置](https://www.npmjs.com/package/tslint-config-airbnb) - Airbnb 风格指南 2378 | 2379 | - [简洁代码的 TSLint 配置](https://www.npmjs.com/package/tslint-clean-code) - 受 [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.ca/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) 影响的 TSLint 规则 2380 | 2381 | - [React 的 TSLint 配置](https://www.npmjs.com/package/tslint-react) - React & JSX 相关的 TSLint 配置 2382 | 2383 | - [TSLint + Prettier](https://www.npmjs.com/package/tslint-config-prettier) - [Prettier](https://github.com/prettier/prettier) 的代码检查规则 2384 | 2385 | - [TypeScript 的 ESLint 规则](https://www.npmjs.com/package/tslint-eslint-rules) - TypeScript 的 ESLint 规则 2386 | 2387 | - [Immutable](https://www.npmjs.com/package/tslint-immutable) - TypeScript 中禁止突变的规则 2388 | 2389 | 也请参考这个伟大的 [TypeScript 风格指南和编码约定](https://basarat.gitbooks.io/typescript/docs/styleguide/styleguide.html) 。 2390 | 2391 | ### 使用一致的大小写 2392 | 2393 | 大小写可以告诉你很多关于你的变量, 函数等等。 这些规则是主观的, 所以你的团队可以选择他们想要的任何东西。 关键是, 无论你选择什么, 只要 *保持一致* 即可。 2394 | 2395 | **不好的:** 2396 | 2397 | ```ts 2398 | const DAYS_IN_WEEK = 7; 2399 | const daysInMonth = 30; 2400 | 2401 | const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 2402 | const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; 2403 | 2404 | function eraseDatabase() {} 2405 | function restore_database() {} 2406 | 2407 | type animal = { /* ... */ } 2408 | type Container = { /* ... */ } 2409 | ``` 2410 | 2411 | **好的:** 2412 | 2413 | ```ts 2414 | const DAYS_IN_WEEK = 7; 2415 | const DAYS_IN_MONTH = 30; 2416 | 2417 | const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 2418 | const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles']; 2419 | 2420 | function eraseDatabase() {} 2421 | function restoreDatabase() {} 2422 | 2423 | type Animal = { /* ... */ } 2424 | type Container = { /* ... */ } 2425 | ``` 2426 | 2427 | 建议类、 接口、 类型和命名空间使用 `PascalCase` 风格, 变量、 函数和类成员使用 `camelCase` 风格。 2428 | 2429 | **[⬆ 返回目录](#目录)** 2430 | 2431 | ### 函数的调用方与被调用方应该靠近 2432 | 2433 | 如果一个函数调用另一个, 则在代码中这两个函数的竖直位置应该靠近。 理想情况下,保持被调用函数在被调用函数的正上方。 我们倾向于从上到下阅读代码, 就像读一章报纸。 由于这个原因, 保持你的代码可 2434 | 以按照这种方式阅读。 2435 | 2436 | **不好的:** 2437 | 2438 | ```ts 2439 | class PerformanceReview { 2440 | constructor(private readonly employee: Employee) { 2441 | } 2442 | 2443 | private lookupPeers() { 2444 | return db.lookup(this.employee.id, 'peers'); 2445 | } 2446 | 2447 | private lookupManager() { 2448 | return db.lookup(this.employee, 'manager'); 2449 | } 2450 | 2451 | private getPeerReviews() { 2452 | const peers = this.lookupPeers(); 2453 | // ... 2454 | } 2455 | 2456 | review() { 2457 | this.getPeerReviews(); 2458 | this.getManagerReview(); 2459 | this.getSelfReview(); 2460 | 2461 | // ... 2462 | } 2463 | 2464 | private getManagerReview() { 2465 | const manager = this.lookupManager(); 2466 | } 2467 | 2468 | private getSelfReview() { 2469 | // ... 2470 | } 2471 | } 2472 | 2473 | const review = new PerformanceReview(employee); 2474 | review.review(); 2475 | ``` 2476 | 2477 | **好的:** 2478 | 2479 | ```ts 2480 | class PerformanceReview { 2481 | constructor(private readonly employee: Employee) { 2482 | } 2483 | 2484 | review() { 2485 | this.getPeerReviews(); 2486 | this.getManagerReview(); 2487 | this.getSelfReview(); 2488 | 2489 | // ... 2490 | } 2491 | 2492 | private getPeerReviews() { 2493 | const peers = this.lookupPeers(); 2494 | // ... 2495 | } 2496 | 2497 | private lookupPeers() { 2498 | return db.lookup(this.employee.id, 'peers'); 2499 | } 2500 | 2501 | private getManagerReview() { 2502 | const manager = this.lookupManager(); 2503 | } 2504 | 2505 | private lookupManager() { 2506 | return db.lookup(this.employee, 'manager'); 2507 | } 2508 | 2509 | private getSelfReview() { 2510 | // ... 2511 | } 2512 | } 2513 | 2514 | const review = new PerformanceReview(employee); 2515 | review.review(); 2516 | ``` 2517 | 2518 | **[⬆ 返回目录](#目录)** 2519 | 2520 | ### 组织导入 2521 | 2522 | 使用简洁易读的 import 语句, 您可以快速查看当前代码的依赖关系。 确保对 `import` 语句应用以下良好实践: 2523 | 2524 | - 导入应当排序并分组; 2525 | - 未使用的导入应当删除; 2526 | - 命名导入应当排序 (比如: `import {A, B, C} from 'foo';`) 2527 | - 导入源应当在分组内排序, 比如: `import * as foo from 'a'; import * as bar from 'b';` 2528 | - 分组导入之间保留一个空行; 2529 | - 分组之间应当遵守下面的顺序: 2530 | - 兼容性填充 (比如: `import 'reflect-metadata';`) 2531 | - Node 内置模块 (比如: `import fs from 'fs';`) 2532 | - 外部模块 (比如: `import { query } from 'itiriri';`) 2533 | - 内部模块 (i.e `import { UserService } from 'src/services/userService';`) 2534 | - 来自父目录的模块 (比如: `import foo from '../foo'; import qux from '../../foo/qux';`) 2535 | - 来自相同目录或同级目录的模块 (比如: `import bar from './bar'; import baz from './bar/baz';`) 2536 | 2537 | **不好的:** 2538 | 2539 | ```ts 2540 | import { TypeDefinition } from '../types/typeDefinition'; 2541 | import { AttributeTypes } from '../model/attribute'; 2542 | import { ApiCredentials, Adapters } from './common/api/authorization'; 2543 | import fs from 'fs'; 2544 | import { ConfigPlugin } from './plugins/config/configPlugin'; 2545 | import { BindingScopeEnum, Container } from 'inversify'; 2546 | import 'reflect-metadata'; 2547 | ``` 2548 | 2549 | **好的:** 2550 | 2551 | ```ts 2552 | import 'reflect-metadata'; 2553 | 2554 | import fs from 'fs'; 2555 | import { BindingScopeEnum, Container } from 'inversify'; 2556 | 2557 | import { AttributeTypes } from '../model/attribute'; 2558 | import { TypeDefinition } from '../types/typeDefinition'; 2559 | 2560 | import { ApiCredentials, Adapters } from './common/api/authorization'; 2561 | import { ConfigPlugin } from './plugins/config/configPlugin'; 2562 | ``` 2563 | 2564 | **[⬆ 返回目录](#目录)** 2565 | 2566 | ### 使用 TypeScript 别名 2567 | 2568 | 通过在 `tsconfig.json` 文件中的 compilerOptions 对象内定义路径和基础路径, 可以创建更漂亮的导入。 2569 | 2570 | 这将避免导入时出现太长的相对路径。 2571 | 2572 | **不好的:** 2573 | 2574 | ```ts 2575 | import { UserService } from '../../../services/UserService'; 2576 | ``` 2577 | 2578 | **好的:** 2579 | 2580 | ```ts 2581 | import { UserService } from '@services/UserService'; 2582 | ``` 2583 | 2584 | ```js 2585 | // tsconfig.json 2586 | ... 2587 | "compilerOptions": { 2588 | ... 2589 | "baseUrl": "src", 2590 | "paths": { 2591 | "@services": ["services/*"] 2592 | } 2593 | ... 2594 | } 2595 | ... 2596 | ``` 2597 | 2598 | **[⬆ 返回目录](#目录)** 2599 | 2600 | ## 注释 2601 | 2602 | 使用注释就意味着代码的表达失败。 代码应该是唯一的事实来源。 2603 | 2604 | > 不是为烂代码添加注释, 而是重写它们。 2605 | > - *Brian W. Kernighan 和 P. J. Plaugher* 2606 | 2607 | ### 倾向于自描述的代码而不是注释 2608 | 2609 | 评论是代码的辩解, 不是要求。 多数情况下, 好的代码就是文档。 2610 | 2611 | **不好的:** 2612 | 2613 | ```ts 2614 | // Check if subscription is active. 2615 | if (subscription.endDate > Date.now) { } 2616 | ``` 2617 | 2618 | **好的:** 2619 | 2620 | ```ts 2621 | const isSubscriptionActive = subscription.endDate > Date.now; 2622 | if (isSubscriptionActive) { /* ... */ } 2623 | ``` 2624 | 2625 | **[⬆ 返回目录](#目录)** 2626 | 2627 | ### 不要在代码库中保存注释掉的代码 2628 | 2629 | 因为有版本控制, 把旧的代码留在历史记录即可 2630 | 2631 | **不好的:** 2632 | 2633 | ```ts 2634 | type User = { 2635 | name: string; 2636 | email: string; 2637 | // age: number; 2638 | // jobPosition: string; 2639 | } 2640 | ``` 2641 | 2642 | **好的:** 2643 | 2644 | ```ts 2645 | type User = { 2646 | name: string; 2647 | email: string; 2648 | } 2649 | ``` 2650 | 2651 | **[⬆ 返回目录](#目录)** 2652 | 2653 | ### 不要有日志式的注释 2654 | 2655 | 记住, 使用版本控制! 不需要僵尸代码, 注释掉的代码, 尤其是日志式的评论。 使用 `git log` 来 2656 | 获取历史记录。 2657 | 2658 | **不好的:** 2659 | 2660 | ```ts 2661 | /** 2662 | * 2016-12-20: Removed monads, didn't understand them (RM) 2663 | * 2016-10-01: Improved using special monads (JP) 2664 | * 2016-02-03: Added type-checking (LI) 2665 | * 2015-03-14: Implemented combine (JR) 2666 | */ 2667 | function combine(a: number, b: number): number { 2668 | return a + b; 2669 | } 2670 | ``` 2671 | 2672 | **好的:** 2673 | 2674 | ```ts 2675 | function combine(a: number, b: number): number { 2676 | return a + b; 2677 | } 2678 | ``` 2679 | 2680 | **[⬆ 返回目录](#目录)** 2681 | 2682 | ### 避免占位符 2683 | 2684 | 它们仅仅添加了干扰。 让函数和变量名称与合适的缩进和格式化为你的代码提供视觉结构。 2685 | 绝大多数 IDE 支持代码折叠, 允许你展开/关闭代码段 (查看 Visual Studio Code [folding regions](https://code.visualstudio.com/updates/v1_17#_folding-regions) ) 。 2686 | 2687 | **不好的:** 2688 | 2689 | ```ts 2690 | //////////////////////////////////////////////////////////////////////////////// 2691 | // Client class 2692 | //////////////////////////////////////////////////////////////////////////////// 2693 | class Client { 2694 | id: number; 2695 | name: string; 2696 | address: Address; 2697 | contact: Contact; 2698 | 2699 | //////////////////////////////////////////////////////////////////////////////// 2700 | // public methods 2701 | //////////////////////////////////////////////////////////////////////////////// 2702 | public describe(): string { 2703 | // ... 2704 | } 2705 | 2706 | //////////////////////////////////////////////////////////////////////////////// 2707 | // private methods 2708 | //////////////////////////////////////////////////////////////////////////////// 2709 | private describeAddress(): string { 2710 | // ... 2711 | } 2712 | 2713 | private describeContact(): string { 2714 | // ... 2715 | } 2716 | }; 2717 | ``` 2718 | 2719 | **好的:** 2720 | 2721 | ```ts 2722 | class Client { 2723 | id: number; 2724 | name: string; 2725 | address: Address; 2726 | contact: Contact; 2727 | 2728 | public describe(): string { 2729 | // ... 2730 | } 2731 | 2732 | private describeAddress(): string { 2733 | // ... 2734 | } 2735 | 2736 | private describeContact(): string { 2737 | // ... 2738 | } 2739 | }; 2740 | ``` 2741 | 2742 | **[⬆ 返回目录](#目录)** 2743 | 2744 | ### TODO 注释 2745 | 2746 | 当你发现你需要在代码中做一些后期改进是, 请使用 `// TODO` 注释。 大多数 IDE 对这种类型的注释有着特殊的支持, 你可以快速的发现全部的 TODO 列表。 2747 | 2748 | 记住, *TODO* 注视并不是烂代码的借口。 2749 | 2750 | **不好的:** 2751 | 2752 | ```ts 2753 | function getActiveSubscriptions(): Promise { 2754 | // ensure `dueDate` is indexed. 2755 | return db.subscriptions.find({ dueDate: { $lte: new Date() } }); 2756 | } 2757 | ``` 2758 | 2759 | **好的:** 2760 | 2761 | ```ts 2762 | function getActiveSubscriptions(): Promise { 2763 | // TODO: ensure `dueDate` is indexed. 2764 | return db.subscriptions.find({ dueDate: { $lte: new Date() } }); 2765 | } 2766 | ``` 2767 | 2768 | **[⬆ 返回目录](#目录)** 2769 | 2770 | ## 翻译 2771 | 2772 | 本文也有其它语言版本: 2773 | 2774 | - ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **巴西葡萄牙语**: [vitorfreitas/clean-code-typescript](https://github.com/vitorfreitas/clean-code-typescript) 2775 | - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **简体中文**: 2776 | - [beginor/clean-code-typescript](https://github.com/beginor/clean-code-typescript) 2777 | - [pipiliang/clean-code-typescript](https://github.com/pipiliang/clean-code-typescript) 2778 | - ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **日文**: [MSakamaki/clean-code-typescript](https://github.com/MSakamaki/clean-code-typescript) 2779 | 2780 | 还有一些语言的版本也正在翻译中: 2781 | 2782 | - ![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) 韩语 2783 | 2784 | 一旦翻译完成, 就会在这里添加链接。 关注这个[讨论](https://github.com/labs42io/clean-code-typescript/issues/15)以获得更多的详情以及进度。 您可以通过将其翻译成您的语言,为* Clean Code *社区做出不可或缺的贡献。 2785 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman --------------------------------------------------------------------------------