├── .gitattributes ├── .github └── FUNDING.yml ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-documentation=false 2 | *.md linguist-language=JavaScript 3 | -------------------------------------------------------------------------------- /.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) 2016 Ryan McDermott 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 代码整洁的 JavaScript 2 | 3 | ## 目录 4 | 5 | 1. [简介](#简介) 6 | 2. [变量](#变量) 7 | 3. [函数](#函数) 8 | 4. [对象和数据结构](#对象和数据结构) 9 | 5. [类](#类) 10 | 6. [SOLID](#solid) 11 | 7. [测试](#测试) 12 | 8. [并发](#并发) 13 | 9. [错误处理](#错误处理) 14 | 10. [格式化](#格式化) 15 | 11. [注释](#注释) 16 | 12. [Translation](#translation) 17 | 18 | ## 简介 19 | 20 | ![一张用你阅读代码时吐槽的数量来评估软件质量的搞笑图片](http://www.osnews.com/images/comics/wtfm.jpg) 21 | 22 | 将源自 Robert C. Martin 的 [*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) 23 | 的软件工程原则适配到 JavaScript 。 这不是一个代码风格指南, 它是一个使用 JavaScript 来生产 24 | 可读的, 可重用的, 以及可重构的软件的指南。 25 | 26 | 这里的每一项原则都不是必须遵守的, 甚至只有更少的能够被广泛认可。 这些仅仅是指南而已, 但是却是 27 | *Clean Code* 作者多年经验的结晶。 28 | 29 | 我们的软件工程行业只有短短的 50 年, 依然有很多要我们去学习。 当软件架构与建筑架构一样古老时, 30 | 也许我们将会有硬性的规则去遵守。 而现在, 让这些指南做为你和你的团队生产的 JavaScript 代码的 31 | 质量的标准。 32 | 33 | 还有一件事: 知道这些指南并不能马上让你成为一个更加出色的软件开发者, 并且使用它们工作多年也并 34 | 不意味着你不再会犯错误。 每一段代码最开始都是草稿, 像湿粘土一样被打造成最终的形态。 最后当我们 35 | 和搭档们一起审查代码时清除那些不完善之处, 不要因为最初需要改善的草稿代码而自责, 而是对那些代 36 | 码下手。 37 | 38 | ## **变量** 39 | 40 | ### 使用有意义并且可读的变量名称 41 | 42 | **不好的:** 43 | ```javascript 44 | const yyyymmdstr = moment().format('YYYY/MM/DD'); 45 | ``` 46 | 47 | **好的:** 48 | ```javascript 49 | const currentDate = moment().format('YYYY/MM/DD'); 50 | ``` 51 | **[⬆ 返回顶部](#代码整洁的-javascript)** 52 | 53 | ### 为相同类型的变量使用相同的词汇 54 | 55 | **不好的:** 56 | ```javascript 57 | getUserInfo(); 58 | getClientData(); 59 | getCustomerRecord(); 60 | ``` 61 | 62 | **好的:** 63 | ```javascript 64 | getUser(); 65 | ``` 66 | **[⬆ 返回顶部](#代码整洁的-javascript)** 67 | 68 | ### 使用可搜索的名称 69 | 70 | 我们要阅读的代码比要写的代码多得多, 所以我们写出的代码的可读性和可搜索性是很重要的。 使用没有 71 | 意义的变量名将会导致我们的程序难于理解, 将会伤害我们的读者, 所以请使用可搜索的变量名。 类似 72 | [buddy.js](https://github.com/danielstjules/buddy.js) 和 [ESLint](https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md) 73 | 的工具可以帮助我们找到未命名的常量。 74 | 75 | **不好的:** 76 | ```javascript 77 | // 艹, 86400000 是什么鬼? 78 | setTimeout(blastOff, 86400000); 79 | 80 | ``` 81 | 82 | **好的:** 83 | ```javascript 84 | // 将它们声明为全局常量 `const` 。 85 | const MILLISECONDS_IN_A_DAY = 86400000; 86 | 87 | setTimeout(blastOff, MILLISECONDS_IN_A_DAY); 88 | 89 | ``` 90 | **[⬆ 返回顶部](#代码整洁的-javascript)** 91 | 92 | ### 使用解释性的变量 93 | **不好的:** 94 | ```javascript 95 | const address = 'One Infinite Loop, Cupertino 95014'; 96 | const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 97 | saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]); 98 | ``` 99 | 100 | **好的:** 101 | ```javascript 102 | const address = 'One Infinite Loop, Cupertino 95014'; 103 | const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 104 | const [, city, zipCode] = address.match(cityZipCodeRegex) || []; 105 | saveCityZipCode(city, zipCode); 106 | ``` 107 | **[⬆ 返回顶部](#代码整洁的-javascript)** 108 | 109 | ### 避免心理映射 110 | 显示比隐式更好 111 | 112 | **不好的:** 113 | ```javascript 114 | const locations = ['Austin', 'New York', 'San Francisco']; 115 | locations.forEach((l) => { 116 | doStuff(); 117 | doSomeOtherStuff(); 118 | // ... 119 | // ... 120 | // ... 121 | // 等等, `l` 是啥? 122 | dispatch(l); 123 | }); 124 | ``` 125 | 126 | **好的:** 127 | ```javascript 128 | const locations = ['Austin', 'New York', 'San Francisco']; 129 | locations.forEach((location) => { 130 | doStuff(); 131 | doSomeOtherStuff(); 132 | // ... 133 | // ... 134 | // ... 135 | dispatch(location); 136 | }); 137 | ``` 138 | **[⬆ 返回顶部](#代码整洁的-javascript)** 139 | 140 | ### 不添加不必要的上下文 141 | 142 | 如果你的类名/对象名有意义, 不要在变量名上再重复。 143 | 144 | **不好的:** 145 | ```javascript 146 | const Car = { 147 | carMake: 'Honda', 148 | carModel: 'Accord', 149 | carColor: 'Blue' 150 | }; 151 | 152 | function paintCar(car) { 153 | car.carColor = 'Red'; 154 | } 155 | ``` 156 | 157 | **好的:** 158 | ```javascript 159 | const Car = { 160 | make: 'Honda', 161 | model: 'Accord', 162 | color: 'Blue' 163 | }; 164 | 165 | function paintCar(car) { 166 | car.color = 'Red'; 167 | } 168 | ``` 169 | **[⬆ 返回顶部](#代码整洁的-javascript)** 170 | 171 | ### 使用默认变量替代短路运算或条件 172 | 173 | **不好的:** 174 | ```javascript 175 | function createMicrobrewery(name) { 176 | const breweryName = name || 'Hipster Brew Co.'; 177 | // ... 178 | } 179 | 180 | ``` 181 | 182 | **好的:** 183 | ```javascript 184 | function createMicrobrewery(breweryName = 'Hipster Brew Co.') { 185 | // ... 186 | } 187 | 188 | ``` 189 | **[⬆ 返回顶部](#代码整洁的-javascript)** 190 | 191 | ## **函数** 192 | 193 | ### 函数参数 (两个以下最理想) 194 | 195 | 限制函数参数的个数是非常重要的, 因为这样将使你的函数容易进行测试。 一旦超过三个参数将会导致组 196 | 合爆炸, 因为你不得不编写大量针对每个参数的测试用例。 197 | 198 | 没有参数是最理想的, 一个或者两个参数也是可以的, 三个参数应该避免, 超过三个应该被重构。 通常, 199 | 如果你有一个超过两个函数的参数, 那就意味着你的函数尝试做太多的事情。 如果不是, 多数情况下一个 200 | 更高级对象可能会满足需求。 201 | 202 | 由于 JavaScript 允许我们不定义类型/模板就可以创建对象, 当你发现你自己需要大量的参数时, 你 203 | 可以使用一个对象。 204 | 205 | **不好的:** 206 | ```javascript 207 | function createMenu(title, body, buttonText, cancellable) { 208 | // ... 209 | } 210 | ``` 211 | 212 | **好的:** 213 | ```javascript 214 | const menuConfig = { 215 | title: 'Foo', 216 | body: 'Bar', 217 | buttonText: 'Baz', 218 | cancellable: true 219 | }; 220 | 221 | function createMenu(config) { 222 | // ... 223 | } 224 | 225 | ``` 226 | **[⬆ 返回顶部](#代码整洁的-javascript)** 227 | 228 | 229 | ### 函数应当只做一件事情 230 | 231 | 这是软件工程中最重要的一条规则, 当函数需要做更多的事情时, 它们将会更难进行编写、 测试和推理。 232 | 当你能将一个函数隔离到只有一个动作, 他们将能够被容易的进行重构并且你的代码将会更容易阅读。 如 233 | 果你严格遵守本指南中的这一条, 你将会领先于许多开发者。 234 | 235 | **不好的:** 236 | ```javascript 237 | function emailClients(clients) { 238 | clients.forEach((client) => { 239 | const clientRecord = database.lookup(client); 240 | if (clientRecord.isActive()) { 241 | email(client); 242 | } 243 | }); 244 | } 245 | ``` 246 | 247 | **好的:** 248 | ```javascript 249 | function emailClients(clients) { 250 | clients 251 | .filter(isClientActive) 252 | .forEach(email); 253 | } 254 | 255 | function isClientActive(client) { 256 | const clientRecord = database.lookup(client); 257 | return clientRecord.isActive(); 258 | } 259 | ``` 260 | **[⬆ 返回顶部](#代码整洁的-javascript)** 261 | 262 | ### 函数名称应该说明它要做什么 263 | 264 | **不好的:** 265 | ```javascript 266 | function addToDate(date, month) { 267 | // ... 268 | } 269 | 270 | const date = new Date(); 271 | 272 | // 很难从函数名看出加了什么 273 | addToDate(date, 1); 274 | ``` 275 | 276 | **好的:** 277 | ```javascript 278 | function addMonthToDate(month, date) { 279 | // ... 280 | } 281 | 282 | const date = new Date(); 283 | addMonthToDate(1, date); 284 | ``` 285 | **[⬆ 返回顶部](#代码整洁的-javascript)** 286 | 287 | ### 函数应该只有一个抽象级别 288 | 289 | 当在你的函数中有多于一个抽象级别时, 你的函数通常做了太多事情。 拆分函数将会提升重用性和测试性。 290 | 291 | **不好的:** 292 | ```javascript 293 | function parseBetterJSAlternative(code) { 294 | const REGEXES = [ 295 | // ... 296 | ]; 297 | 298 | const statements = code.split(' '); 299 | const tokens = []; 300 | REGEXES.forEach((REGEX) => { 301 | statements.forEach((statement) => { 302 | // ... 303 | }); 304 | }); 305 | 306 | const ast = []; 307 | tokens.forEach((token) => { 308 | // lex... 309 | }); 310 | 311 | ast.forEach((node) => { 312 | // parse... 313 | }); 314 | } 315 | ``` 316 | 317 | **好的:** 318 | ```javascript 319 | function tokenize(code) { 320 | const REGEXES = [ 321 | // ... 322 | ]; 323 | 324 | const statements = code.split(' '); 325 | const tokens = []; 326 | REGEXES.forEach((REGEX) => { 327 | statements.forEach((statement) => { 328 | tokens.push( /* ... */ ); 329 | }); 330 | }); 331 | 332 | return tokens; 333 | } 334 | 335 | function lexer(tokens) { 336 | const ast = []; 337 | tokens.forEach((token) => { 338 | ast.push( /* ... */ ); 339 | }); 340 | 341 | return ast; 342 | } 343 | 344 | function parseBetterJSAlternative(code) { 345 | const tokens = tokenize(code); 346 | const ast = lexer(tokens); 347 | ast.forEach((node) => { 348 | // parse... 349 | }); 350 | } 351 | ``` 352 | **[⬆ 返回顶部](#代码整洁的-javascript)** 353 | 354 | ### 移除冗余代码 355 | 356 | 竭尽你的全力去避免冗余代码。 冗余代码是不好的, 因为它意味着当你需要修改一些逻辑时会有多个地方 357 | 需要修改。 358 | 359 | 想象一下你在经营一家餐馆, 你需要记录所有的库存西红柿, 洋葱, 大蒜, 各种香料等等。 如果你有多 360 | 个记录列表, 当你用西红柿做一道菜时你得更新多个列表。 如果你只有一个列表, 就只有一个地方需要更 361 | 新! 362 | 363 | 你有冗余代码通常是因为你有两个或多个稍微不同的东西, 它们共享大部分, 但是它们的不同之处迫使你使 364 | 用两个或更多独立的函数来处理大部分相同的东西。 移除冗余代码意味着创建一个可以处理这些不同之处的 365 | 抽象的函数/模块/类。 366 | 367 | 让这个抽象正确是关键的, 这是为什么要你遵循 *Classes* 那一章的 SOLID 的原因。 不好的抽象比冗 368 | 余代码更差, 所以要谨慎行事。 既然已经这么说了, 如果你能够做出一个好的抽象, 才去做。 不要重复 369 | 你自己, 否则你会发现当你要修改一个东西时时刻需要修改多个地方。 370 | 371 | **不好的:** 372 | ```javascript 373 | function showDeveloperList(developers) { 374 | developers.forEach((developer) => { 375 | const expectedSalary = developer.calculateExpectedSalary(); 376 | const experience = developer.getExperience(); 377 | const githubLink = developer.getGithubLink(); 378 | const data = { 379 | expectedSalary, 380 | experience, 381 | githubLink 382 | }; 383 | 384 | render(data); 385 | }); 386 | } 387 | 388 | function showManagerList(managers) { 389 | managers.forEach((manager) => { 390 | const expectedSalary = manager.calculateExpectedSalary(); 391 | const experience = manager.getExperience(); 392 | const portfolio = manager.getMBAProjects(); 393 | const data = { 394 | expectedSalary, 395 | experience, 396 | portfolio 397 | }; 398 | 399 | render(data); 400 | }); 401 | } 402 | ``` 403 | 404 | **好的:** 405 | ```javascript 406 | function showList(employees) { 407 | employees.forEach((employee) => { 408 | const expectedSalary = employee.calculateExpectedSalary(); 409 | const experience = employee.getExperience(); 410 | 411 | let portfolio = employee.getGithubLink(); 412 | 413 | if (employee.type === 'manager') { 414 | portfolio = employee.getMBAProjects(); 415 | } 416 | 417 | const data = { 418 | expectedSalary, 419 | experience, 420 | portfolio 421 | }; 422 | 423 | render(data); 424 | }); 425 | } 426 | ``` 427 | **[⬆ 返回顶部](#代码整洁的-javascript)** 428 | 429 | ### 使用 Object.assign 设置默认对象 430 | 431 | **不好的:** 432 | ```javascript 433 | const menuConfig = { 434 | title: null, 435 | body: 'Bar', 436 | buttonText: null, 437 | cancellable: true 438 | }; 439 | 440 | function createMenu(config) { 441 | config.title = config.title || 'Foo'; 442 | config.body = config.body || 'Bar'; 443 | config.buttonText = config.buttonText || 'Baz'; 444 | config.cancellable = config.cancellable === undefined ? config.cancellable : true; 445 | } 446 | 447 | createMenu(menuConfig); 448 | ``` 449 | 450 | **好的:** 451 | ```javascript 452 | const menuConfig = { 453 | title: 'Order', 454 | // User did not include 'body' key 455 | buttonText: 'Send', 456 | cancellable: true 457 | }; 458 | 459 | function createMenu(config) { 460 | config = Object.assign({ 461 | title: 'Foo', 462 | body: 'Bar', 463 | buttonText: 'Baz', 464 | cancellable: true 465 | }, config); 466 | 467 | // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} 468 | // ... 469 | } 470 | 471 | createMenu(menuConfig); 472 | ``` 473 | **[⬆ 返回顶部](#代码整洁的-javascript)** 474 | 475 | 476 | ### 不要使用标记位做为函数参数 477 | 478 | 标记位是告诉你的用户这个函数做了不只一件事情。 函数应该只做一件事情。 如果你的函数因为一个布尔值 479 | 出现不同的代码路径, 请拆分它们。 480 | 481 | **不好的:** 482 | ```javascript 483 | function createFile(name, temp) { 484 | if (temp) { 485 | fs.create(`./temp/${name}`); 486 | } else { 487 | fs.create(name); 488 | } 489 | } 490 | ``` 491 | 492 | **好的:** 493 | ```javascript 494 | function createFile(name) { 495 | fs.create(name); 496 | } 497 | 498 | function createTempFile(name) { 499 | createFile(`./temp/${name}`); 500 | } 501 | ``` 502 | **[⬆ 返回顶部](#代码整洁的-javascript)** 503 | 504 | ### 避免副作用 505 | 506 | 如果一个函数做了除接受一个值然后返回一个值或多个值之外的任何事情, 它将会产生副作用, 它可能是 507 | 写入一个文件, 修改一个全局变量, 或者意外的把你所有的钱连接到一个陌生人那里。 508 | 509 | 现在在你的程序中确实偶尔需要副作用, 就像上面的代码, 你也许需要写入到一个文件, 你需要做的是集 510 | 中化你要做的事情, 不要让多个函数或者类写入一个特定的文件, 用一个服务来实现它, 一个并且只有一 511 | 个。 512 | 513 | 重点是避免这些常见的易犯的错误, 比如在对象之间共享状态而不使用任何结构, 使用任何地方都可以写入 514 | 的可变的数据类型, 没有集中化导致副作用。 如果你能做到这些, 那么你将会比其它的码农大军更加幸福。 515 | 516 | **不好的:** 517 | ```javascript 518 | // Global variable referenced by following function. 519 | // 全局变量被下面的函数引用 520 | // If we had another function that used this name, now it'd be an array and it 521 | // could break it. 522 | // 如果我们有另一个函数使用这个 name , 现在它应该是一个数组, 这可能会出现错误。 523 | let name = 'Ryan McDermott'; 524 | 525 | function splitIntoFirstAndLastName() { 526 | name = name.split(' '); 527 | } 528 | 529 | splitIntoFirstAndLastName(); 530 | 531 | console.log(name); // ['Ryan', 'McDermott']; 532 | ``` 533 | 534 | **好的:** 535 | ```javascript 536 | function splitIntoFirstAndLastName(name) { 537 | return name.split(' '); 538 | } 539 | 540 | const name = 'Ryan McDermott'; 541 | const newName = splitIntoFirstAndLastName(name); 542 | 543 | console.log(name); // 'Ryan McDermott'; 544 | console.log(newName); // ['Ryan', 'McDermott']; 545 | ``` 546 | **[⬆ 返回顶部](#代码整洁的-javascript)** 547 | 548 | ### 不要写入全局函数 549 | 550 | 污染全局在 JavaScript 中是一个不好的做法, 因为你可能会和另外一个类库冲突, 你的 API 的用户 551 | 可能不够聪明, 直到他们得到在生产环境得到一个异常。 让我们来考虑这样一个例子: 假设你要扩展 552 | JavaScript 的 原生 `Array` , 添加一个可以显示两个数组的不同之处的 `diff` 方法, 你可以在 553 | `Array.prototype` 中写一个新的方法, 但是它可能会和尝试做相同事情的其它类库发生冲突。 如果有 554 | 另外一个类库仅仅使用 `diff` 方法来查找数组的第一个元素和最后一个元素之间的不同之处呢? 这就是 555 | 为什么使用 ES2015/ES6 的类是一个更好的做法的原因, 只要简单的扩展全局的 `Array` 即可。 556 | 557 | **不好的:** 558 | ```javascript 559 | Array.prototype.diff = function diff(comparisonArray) { 560 | const hash = new Set(comparisonArray); 561 | return this.filter(elem => !hash.has(elem)); 562 | }; 563 | ``` 564 | 565 | **好的:** 566 | ```javascript 567 | class SuperArray extends Array { 568 | diff(comparisonArray) { 569 | const hash = new Set(comparisonArray); 570 | return this.filter(elem => !hash.has(elem)); 571 | } 572 | } 573 | ``` 574 | **[⬆ 返回顶部](#代码整洁的-javascript)** 575 | 576 | ### 函数式编程优于指令式编程 577 | 578 | JavaScript 不是 Haskell 那种方式的函数式语言, 但是它有它的函数式风格。 函数式语言更加简洁 579 | 并且更容易进行测试, 当你可以使用函数式编程风格时请尽情使用。 580 | 581 | **不好的:** 582 | ```javascript 583 | const programmerOutput = [ 584 | { 585 | name: 'Uncle Bobby', 586 | linesOfCode: 500 587 | }, { 588 | name: 'Suzie Q', 589 | linesOfCode: 1500 590 | }, { 591 | name: 'Jimmy Gosling', 592 | linesOfCode: 150 593 | }, { 594 | name: 'Gracie Hopper', 595 | linesOfCode: 1000 596 | } 597 | ]; 598 | 599 | let totalOutput = 0; 600 | 601 | for (let i = 0; i < programmerOutput.length; i++) { 602 | totalOutput += programmerOutput[i].linesOfCode; 603 | } 604 | ``` 605 | 606 | **好的:** 607 | ```javascript 608 | const programmerOutput = [ 609 | { 610 | name: 'Uncle Bobby', 611 | linesOfCode: 500 612 | }, { 613 | name: 'Suzie Q', 614 | linesOfCode: 1500 615 | }, { 616 | name: 'Jimmy Gosling', 617 | linesOfCode: 150 618 | }, { 619 | name: 'Gracie Hopper', 620 | linesOfCode: 1000 621 | } 622 | ]; 623 | 624 | const totalOutput = programmerOutput 625 | .map((programmer) => programmer.linesOfCode) 626 | .reduce((acc, linesOfCode) => acc + linesOfCode, 0); 627 | ``` 628 | **[⬆ 返回顶部](#代码整洁的-javascript)** 629 | 630 | ### 封装条件语句 631 | 632 | **不好的:** 633 | ```javascript 634 | if (fsm.state === 'fetching' && isEmpty(listNode)) { 635 | // ... 636 | } 637 | ``` 638 | 639 | **好的:** 640 | ```javascript 641 | function shouldShowSpinner(fsm, listNode) { 642 | return fsm.state === 'fetching' && isEmpty(listNode); 643 | } 644 | 645 | if (shouldShowSpinner(fsmInstance, listNodeInstance)) { 646 | // ... 647 | } 648 | ``` 649 | **[⬆ 返回顶部](#代码整洁的-javascript)** 650 | 651 | ### 避免负面条件 652 | 653 | **不好的:** 654 | ```javascript 655 | function isDOMNodeNotPresent(node) { 656 | // ... 657 | } 658 | 659 | if (!isDOMNodeNotPresent(node)) { 660 | // ... 661 | } 662 | ``` 663 | 664 | **好的:** 665 | ```javascript 666 | function isDOMNodePresent(node) { 667 | // ... 668 | } 669 | 670 | if (isDOMNodePresent(node)) { 671 | // ... 672 | } 673 | ``` 674 | **[⬆ 返回顶部](#代码整洁的-javascript)** 675 | 676 | ### 避免条件语句 677 | 678 | 这看起来似乎是一个不可能的任务。 第一次听到这个时, 多数人会说: “没有 `if` 语句还能期望我干 679 | 啥呢”, 答案是多数情况下你可以使用多态来完成同样的任务。 第二个问题通常是 “好了, 那么做很棒, 680 | 但是我为什么想要那样做呢”, 答案是我们学到的上一条代码整洁之道的理念: 一个函数应当只做一件事情。 681 | 当你有使用 `if` 语句的类/函数是, 你在告诉你的用户你的函数做了不止一件事情。 记住: 只做一件 682 | 事情。 683 | 684 | **不好的:** 685 | ```javascript 686 | class Airplane { 687 | // ... 688 | getCruisingAltitude() { 689 | switch (this.type) { 690 | case '777': 691 | return this.getMaxAltitude() - this.getPassengerCount(); 692 | case 'Air Force One': 693 | return this.getMaxAltitude(); 694 | case 'Cessna': 695 | return this.getMaxAltitude() - this.getFuelExpenditure(); 696 | } 697 | } 698 | } 699 | ``` 700 | 701 | **好的:** 702 | ```javascript 703 | class Airplane { 704 | // ... 705 | } 706 | 707 | class Boeing777 extends Airplane { 708 | // ... 709 | getCruisingAltitude() { 710 | return this.getMaxAltitude() - this.getPassengerCount(); 711 | } 712 | } 713 | 714 | class AirForceOne extends Airplane { 715 | // ... 716 | getCruisingAltitude() { 717 | return this.getMaxAltitude(); 718 | } 719 | } 720 | 721 | class Cessna extends Airplane { 722 | // ... 723 | getCruisingAltitude() { 724 | return this.getMaxAltitude() - this.getFuelExpenditure(); 725 | } 726 | } 727 | ``` 728 | **[⬆ 返回顶部](#代码整洁的-javascript)** 729 | 730 | ### 避免类型检查 (part 1) 731 | 732 | JavaScript 是无类型的, 这意味着你的函数能接受任何类型的参数。 但是有时又会被这种自由咬伤, 733 | 于是又尝试在你的函数中做类型检查。 有很多种方式来避免这个, 第一个要考虑的是一致的 API 。 734 | 735 | **不好的:** 736 | ```javascript 737 | function travelToTexas(vehicle) { 738 | if (vehicle instanceof Bicycle) { 739 | vehicle.peddle(this.currentLocation, new Location('texas')); 740 | } else if (vehicle instanceof Car) { 741 | vehicle.drive(this.currentLocation, new Location('texas')); 742 | } 743 | } 744 | ``` 745 | 746 | **好的:** 747 | ```javascript 748 | function travelToTexas(vehicle) { 749 | vehicle.move(this.currentLocation, new Location('texas')); 750 | } 751 | ``` 752 | **[⬆ 返回顶部](#代码整洁的-javascript)** 753 | 754 | ### 避免类型检查 (part 2) 755 | 756 | 如果你使用原始的字符串、 整数和数组, 并且你不能使用多态, 但是你依然感觉到有类型检查的需要, 757 | 你应该考虑使用 TypeScript 。 它是一个常规 JavaScript 的优秀的替代品, 因为它在标准的 JavaScript 758 | 语法之上为你提供静态类型。 对常规 JavaScript 做人工类型检查的问题是需要大量的冗词来仿造类型安 759 | 全而不缺失可读性。 保持你的 JavaScript 简洁, 编写良好的测试, 并有良好的代码审阅, 否则使用 760 | TypeScript (就像我说的, 它是一个伟大的替代品)来完成这些。 761 | 762 | **不好的:** 763 | ```javascript 764 | function combine(val1, val2) { 765 | if (typeof val1 === 'number' && typeof val2 === 'number' || 766 | typeof val1 === 'string' && typeof val2 === 'string') { 767 | return val1 + val2; 768 | } 769 | 770 | throw new Error('Must be of type String or Number'); 771 | } 772 | ``` 773 | 774 | **好的:** 775 | ```javascript 776 | function combine(val1, val2) { 777 | return val1 + val2; 778 | } 779 | ``` 780 | **[⬆ 返回顶部](#代码整洁的-javascript)** 781 | 782 | ### 不要过度优化 783 | 784 | 现代化浏览器运行时在幕后做大量的优化, 在大多数的时间, 做优化就是在浪费你的时间。 [这些是好的 785 | 资源](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers), 用来 786 | 查看那些地方需要优化。 为这些而优化, 直到他们被修正。 787 | 788 | **不好的:** 789 | ```javascript 790 | 791 | // On old browsers, each iteration with uncached `list.length` would be costly 792 | // because of `list.length` recomputation. In modern browsers, this is optimized. 793 | // 在旧的浏览器上, 每次循环 `list.length` 都没有被缓存, 会导致不必要的开销, 因为要重新计 794 | // 算 `list.length` 。 在现代化浏览器上, 这个已经被优化了。 795 | for (let i = 0, len = list.length; i < len; i++) { 796 | // ... 797 | } 798 | ``` 799 | 800 | **好的:** 801 | ```javascript 802 | for (let i = 0; i < list.length; i++) { 803 | // ... 804 | } 805 | ``` 806 | **[⬆ 返回顶部](#代码整洁的-javascript)** 807 | 808 | ### 移除僵尸代码 809 | 810 | 僵死代码和冗余代码同样糟糕。 没有理由在代码库中保存它。 如果它不会被调用, 就删掉它。 当你需要 811 | 它时, 它依然保存在版本历史记录中。 812 | 813 | **不好的:** 814 | ```javascript 815 | function oldRequestModule(url) { 816 | // ... 817 | } 818 | 819 | function newRequestModule(url) { 820 | // ... 821 | } 822 | 823 | const req = newRequestModule; 824 | inventoryTracker('apples', req, 'www.inventory-awesome.io'); 825 | 826 | ``` 827 | 828 | **好的:** 829 | ```javascript 830 | function newRequestModule(url) { 831 | // ... 832 | } 833 | 834 | const req = newRequestModule; 835 | inventoryTracker('apples', req, 'www.inventory-awesome.io'); 836 | ``` 837 | **[⬆ 返回顶部](#代码整洁的-javascript)** 838 | 839 | ## **对象和数据结构** 840 | 841 | ### 使用 getters 和 setters 842 | 843 | JavaScript 没有接口或类型, 所以坚持这个模式是非常困难的, 因为我们没有 `public` 和 `private` 844 | 关键字。 正因为如此, 使用 getters 和 setters 来访问对象上的数据比简单的在一个对象上查找属性 845 | 要好得多。 “为什么?” 你可能会问, 好吧, 原因请看下面的列表: 846 | 847 | * 当你想在获取一个对象属性的背后做更多的事情时, 你不需要在代码库中查找和修改每一处访问; 848 | * 使用 `set` 可以让添加验证变得容易; 849 | * 封装内部实现; 850 | * 使用 getting 和 setting 时, 容易添加日志和错误处理; 851 | * 继承这个类, 你可以重写默认功能; 852 | * 你可以延迟加载对象的属性, 比如说从服务器获取。 853 | 854 | **不好的:** 855 | ```javascript 856 | class BankAccount { 857 | constructor() { 858 | this.balance = 1000; 859 | } 860 | } 861 | 862 | const bankAccount = new BankAccount(); 863 | 864 | // Buy shoes... 865 | bankAccount.balance -= 100; 866 | ``` 867 | 868 | **好的:** 869 | ```javascript 870 | class BankAccount { 871 | constructor(balance = 1000) { 872 | this._balance = balance; 873 | } 874 | 875 | // It doesn't have to be prefixed with `get` or `set` to be a getter/setter 876 | set balance(amount) { 877 | if (verifyIfAmountCanBeSetted(amount)) { 878 | this._balance = amount; 879 | } 880 | } 881 | 882 | get balance() { 883 | return this._balance; 884 | } 885 | 886 | verifyIfAmountCanBeSetted(val) { 887 | // ... 888 | } 889 | } 890 | 891 | const bankAccount = new BankAccount(); 892 | 893 | // Buy shoes... 894 | bankAccount.balance -= shoesPrice; 895 | 896 | // Get balance 897 | let balance = bankAccount.balance; 898 | 899 | ``` 900 | **[⬆ 返回顶部](#代码整洁的-javascript)** 901 | 902 | 903 | ### 让对象拥有私有成员 904 | 这个可以通过闭包来实现(针对 ES5 或更低)。 905 | 906 | **不好的:** 907 | ```javascript 908 | 909 | const Employee = function(name) { 910 | this.name = name; 911 | }; 912 | 913 | Employee.prototype.getName = function getName() { 914 | return this.name; 915 | }; 916 | 917 | const employee = new Employee('John Doe'); 918 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 919 | delete employee.name; 920 | console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined 921 | ``` 922 | 923 | **好的:** 924 | ```javascript 925 | const Employee = function (name) { 926 | this.getName = function getName() { 927 | return name; 928 | }; 929 | }; 930 | 931 | const employee = new Employee('John Doe'); 932 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 933 | delete employee.name; 934 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 935 | ``` 936 | **[⬆ 返回顶部](#代码整洁的-javascript)** 937 | 938 | 939 | ## **类** 940 | 941 | ### ES2015/ES6 类优先与 ES5 纯函数 942 | 943 | 很难为经典的 ES5 类创建可读的的继承、 构造和方法定义。 如果你需要继承(并且感到奇怪为啥你不需 944 | 要), 则优先用 ES2015/ES6的类。 不过, 短小的函数优先于类, 直到你发现你需要更大并且更复杂的 945 | 对象。 946 | 947 | **不好的:** 948 | ```javascript 949 | const Animal = function(age) { 950 | if (!(this instanceof Animal)) { 951 | throw new Error('Instantiate Animal with `new`'); 952 | } 953 | 954 | this.age = age; 955 | }; 956 | 957 | Animal.prototype.move = function move() {}; 958 | 959 | const Mammal = function(age, furColor) { 960 | if (!(this instanceof Mammal)) { 961 | throw new Error('Instantiate Mammal with `new`'); 962 | } 963 | 964 | Animal.call(this, age); 965 | this.furColor = furColor; 966 | }; 967 | 968 | Mammal.prototype = Object.create(Animal.prototype); 969 | Mammal.prototype.constructor = Mammal; 970 | Mammal.prototype.liveBirth = function liveBirth() {}; 971 | 972 | const Human = function(age, furColor, languageSpoken) { 973 | if (!(this instanceof Human)) { 974 | throw new Error('Instantiate Human with `new`'); 975 | } 976 | 977 | Mammal.call(this, age, furColor); 978 | this.languageSpoken = languageSpoken; 979 | }; 980 | 981 | Human.prototype = Object.create(Mammal.prototype); 982 | Human.prototype.constructor = Human; 983 | Human.prototype.speak = function speak() {}; 984 | ``` 985 | 986 | **好的:** 987 | ```javascript 988 | class Animal { 989 | constructor(age) { 990 | this.age = age; 991 | } 992 | 993 | move() { /* ... */ } 994 | } 995 | 996 | class Mammal extends Animal { 997 | constructor(age, furColor) { 998 | super(age); 999 | this.furColor = furColor; 1000 | } 1001 | 1002 | liveBirth() { /* ... */ } 1003 | } 1004 | 1005 | class Human extends Mammal { 1006 | constructor(age, furColor, languageSpoken) { 1007 | super(age, furColor); 1008 | this.languageSpoken = languageSpoken; 1009 | } 1010 | 1011 | speak() { /* ... */ } 1012 | } 1013 | ``` 1014 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1015 | 1016 | ### 使用方法链 1017 | 1018 | 这个模式在 JavaScript 中是非常有用的, 并且你可以在许多类库比如 jQuery 和 Lodash 中见到。 1019 | 它使你的代码变得富有表现力, 并减少啰嗦。 因为这个原因, 我说, 使用方法链然后再看看你的代码 1020 | 会变得多么简洁。 在你的类/方法中, 简单的在每个方法的最后返回 `this` , 然后你就能把这个类的 1021 | 其它方法链在一起。 1022 | 1023 | **不好的:** 1024 | ```javascript 1025 | class Car { 1026 | constructor() { 1027 | this.make = 'Honda'; 1028 | this.model = 'Accord'; 1029 | this.color = 'white'; 1030 | } 1031 | 1032 | setMake(make) { 1033 | this.make = make; 1034 | } 1035 | 1036 | setModel(model) { 1037 | this.model = model; 1038 | } 1039 | 1040 | setColor(color) { 1041 | this.color = color; 1042 | } 1043 | 1044 | save() { 1045 | console.log(this.make, this.model, this.color); 1046 | } 1047 | } 1048 | 1049 | const car = new Car(); 1050 | car.setColor('pink'); 1051 | car.setMake('Ford'); 1052 | car.setModel('F-150'); 1053 | car.save(); 1054 | ``` 1055 | 1056 | **好的:** 1057 | ```javascript 1058 | class Car { 1059 | constructor() { 1060 | this.make = 'Honda'; 1061 | this.model = 'Accord'; 1062 | this.color = 'white'; 1063 | } 1064 | 1065 | setMake(make) { 1066 | this.make = make; 1067 | // NOTE: Returning this for chaining 1068 | return this; 1069 | } 1070 | 1071 | setModel(model) { 1072 | this.model = model; 1073 | // NOTE: Returning this for chaining 1074 | return this; 1075 | } 1076 | 1077 | setColor(color) { 1078 | this.color = color; 1079 | // NOTE: Returning this for chaining 1080 | return this; 1081 | } 1082 | 1083 | save() { 1084 | console.log(this.make, this.model, this.color); 1085 | // NOTE: Returning this for chaining 1086 | return this; 1087 | } 1088 | } 1089 | 1090 | const car = new Car() 1091 | .setColor('pink') 1092 | .setMake('Ford') 1093 | .setModel('F-150') 1094 | .save(); 1095 | ``` 1096 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1097 | 1098 | ### 组合优先于继承 1099 | 1100 | 正如[*设计模式四人帮*](https://en.wikipedia.org/wiki/Design_Patterns)所述, 如果可能, 1101 | 你应该优先使用组合而不是继承。 有许多好的理由去使用继承, 也有许多好的理由去使用组合。这个格言 1102 | 的重点是, 如果你本能的观点是继承, 那么请想一下组合能否更好的为你的问题建模。 很多情况下它真的 1103 | 可以。 1104 | 1105 | 那么你也许会这样想, “我什么时候改使用继承?” 这取决于你手上的问题, 不过这儿有一个像样的列表说 1106 | 明什么时候继承比组合更好用: 1107 | 1108 | 1. 你的继承表示"是一个"的关系而不是"有一个"的关系(人类->动物 vs 用户->用户详情); 1109 | 2. 你可以重用来自基类的代码(人可以像所有动物一样行动); 1110 | 3. 你想通过基类对子类进行全局的修改(改变所有动物行动时的热量消耗); 1111 | 1112 | **不好的:** 1113 | ```javascript 1114 | class Employee { 1115 | constructor(name, email) { 1116 | this.name = name; 1117 | this.email = email; 1118 | } 1119 | 1120 | // ... 1121 | } 1122 | 1123 | // 不好是因为雇员“有”税率数据, EmployeeTaxData 不是一个 Employee 类型。 1124 | class EmployeeTaxData extends Employee { 1125 | constructor(ssn, salary) { 1126 | super(); 1127 | this.ssn = ssn; 1128 | this.salary = salary; 1129 | } 1130 | 1131 | // ... 1132 | } 1133 | ``` 1134 | 1135 | **好的:** 1136 | ```javascript 1137 | class EmployeeTaxData { 1138 | constructor(ssn, salary) { 1139 | this.ssn = ssn; 1140 | this.salary = salary; 1141 | } 1142 | 1143 | // ... 1144 | } 1145 | 1146 | class Employee { 1147 | constructor(name, email) { 1148 | this.name = name; 1149 | this.email = email; 1150 | } 1151 | 1152 | setTaxData(ssn, salary) { 1153 | this.taxData = new EmployeeTaxData(ssn, salary); 1154 | } 1155 | // ... 1156 | } 1157 | ``` 1158 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1159 | 1160 | ## **SOLID** 1161 | 1162 | ### 单一职责原则 (SRP) 1163 | 1164 | 正如代码整洁之道所述, “永远不要有超过一个理由来修改一个类”。 给一个类塞满许多功能, 就像你在航 1165 | 班上只能带一个行李箱一样, 这样做的问题你的类不会有理想的内聚性, 将会有太多的理由来对它进行修改。 1166 | 最小化需要修改一个类的次数时很重要的, 因为如果一个类拥有太多的功能, 一旦你修改它的一小部分, 1167 | 将会很难弄清楚会对代码库中的其它模块造成什么影响。 1168 | 1169 | **不好的:** 1170 | ```javascript 1171 | class UserSettings { 1172 | constructor(user) { 1173 | this.user = user; 1174 | } 1175 | 1176 | changeSettings(settings) { 1177 | if (this.verifyCredentials()) { 1178 | // ... 1179 | } 1180 | } 1181 | 1182 | verifyCredentials() { 1183 | // ... 1184 | } 1185 | } 1186 | ``` 1187 | 1188 | **好的:** 1189 | ```javascript 1190 | class UserAuth { 1191 | constructor(user) { 1192 | this.user = user; 1193 | } 1194 | 1195 | verifyCredentials() { 1196 | // ... 1197 | } 1198 | } 1199 | 1200 | 1201 | class UserSettings { 1202 | constructor(user) { 1203 | this.user = user; 1204 | this.auth = new UserAuth(user); 1205 | } 1206 | 1207 | changeSettings(settings) { 1208 | if (this.auth.verifyCredentials()) { 1209 | // ... 1210 | } 1211 | } 1212 | } 1213 | ``` 1214 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1215 | 1216 | ### 开闭原则 (OCP) 1217 | 1218 | Bertrand Meyer 说过, “软件实体 (类, 模块, 函数等) 应该为扩展开放, 但是为修改关闭。” 这 1219 | 是什么意思呢? 这个原则基本上说明了你应该允许用户添加功能而不必修改现有的代码。 1220 | 1221 | **不好的:** 1222 | ```javascript 1223 | class AjaxAdapter extends Adapter { 1224 | constructor() { 1225 | super(); 1226 | this.name = 'ajaxAdapter'; 1227 | } 1228 | } 1229 | 1230 | class NodeAdapter extends Adapter { 1231 | constructor() { 1232 | super(); 1233 | this.name = 'nodeAdapter'; 1234 | } 1235 | } 1236 | 1237 | class HttpRequester { 1238 | constructor(adapter) { 1239 | this.adapter = adapter; 1240 | } 1241 | 1242 | fetch(url) { 1243 | if (this.adapter.name === 'ajaxAdapter') { 1244 | return makeAjaxCall(url).then((response) => { 1245 | // transform response and return 1246 | }); 1247 | } else if (this.adapter.name === 'httpNodeAdapter') { 1248 | return makeHttpCall(url).then((response) => { 1249 | // transform response and return 1250 | }); 1251 | } 1252 | } 1253 | } 1254 | 1255 | function makeAjaxCall(url) { 1256 | // request and return promise 1257 | } 1258 | 1259 | function makeHttpCall(url) { 1260 | // request and return promise 1261 | } 1262 | ``` 1263 | 1264 | **好的:** 1265 | ```javascript 1266 | class AjaxAdapter extends Adapter { 1267 | constructor() { 1268 | super(); 1269 | this.name = 'ajaxAdapter'; 1270 | } 1271 | 1272 | request(url) { 1273 | // request and return promise 1274 | } 1275 | } 1276 | 1277 | class NodeAdapter extends Adapter { 1278 | constructor() { 1279 | super(); 1280 | this.name = 'nodeAdapter'; 1281 | } 1282 | 1283 | request(url) { 1284 | // request and return promise 1285 | } 1286 | } 1287 | 1288 | class HttpRequester { 1289 | constructor(adapter) { 1290 | this.adapter = adapter; 1291 | } 1292 | 1293 | fetch(url) { 1294 | return this.adapter.request(url).then((response) => { 1295 | // transform response and return 1296 | }); 1297 | } 1298 | } 1299 | ``` 1300 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1301 | 1302 | ### 里氏代换原则 (LSP) 1303 | 1304 | 这是针对一个非常简单的里面的一个恐怖意图, 它的正式定义是: “如果 S 是 T 的一个子类型, 那么类 1305 | 型为 T 的对象可以被类型为 S 的对象替换(例如, 类型为 S 的对象可作为类型为 T 的替代品)而不需 1306 | 要修改目标程序的期望性质 (正确性、 任务执行性等)。” 这甚至是个恐怖的定义。 1307 | 1308 | 最好的解释是, 如果你有一个基类和一个子类, 那个基类和字类可以互换而不会产生不正确的结果。 这可 1309 | 能还有有些疑惑, 让我们来看一下这个经典的正方形与矩形的例子。 从数学上说, 一个正方形是一个矩形, 1310 | 但是你用 "is-a" 的关系用继承来实现, 你将很快遇到麻烦。 1311 | 1312 | **不好的:** 1313 | ```javascript 1314 | class Rectangle { 1315 | constructor() { 1316 | this.width = 0; 1317 | this.height = 0; 1318 | } 1319 | 1320 | setColor(color) { 1321 | // ... 1322 | } 1323 | 1324 | render(area) { 1325 | // ... 1326 | } 1327 | 1328 | setWidth(width) { 1329 | this.width = width; 1330 | } 1331 | 1332 | setHeight(height) { 1333 | this.height = height; 1334 | } 1335 | 1336 | getArea() { 1337 | return this.width * this.height; 1338 | } 1339 | } 1340 | 1341 | class Square extends Rectangle { 1342 | setWidth(width) { 1343 | this.width = width; 1344 | this.height = width; 1345 | } 1346 | 1347 | setHeight(height) { 1348 | this.width = height; 1349 | this.height = height; 1350 | } 1351 | } 1352 | 1353 | function renderLargeRectangles(rectangles) { 1354 | rectangles.forEach((rectangle) => { 1355 | rectangle.setWidth(4); 1356 | rectangle.setHeight(5); 1357 | const area = rectangle.getArea(); // BAD: Will return 25 for Square. Should be 20. 1358 | rectangle.render(area); 1359 | }); 1360 | } 1361 | 1362 | const rectangles = [new Rectangle(), new Rectangle(), new Square()]; 1363 | renderLargeRectangles(rectangles); 1364 | ``` 1365 | 1366 | **好的:** 1367 | ```javascript 1368 | class Shape { 1369 | setColor(color) { 1370 | // ... 1371 | } 1372 | 1373 | render(area) { 1374 | // ... 1375 | } 1376 | } 1377 | 1378 | class Rectangle extends Shape { 1379 | constructor(width, height) { 1380 | super(); 1381 | this.width = width; 1382 | this.height = height; 1383 | } 1384 | 1385 | getArea() { 1386 | return this.width * this.height; 1387 | } 1388 | } 1389 | 1390 | class Square extends Shape { 1391 | constructor(length) { 1392 | super(); 1393 | this.length = length; 1394 | } 1395 | 1396 | getArea() { 1397 | return this.length * this.length; 1398 | } 1399 | } 1400 | 1401 | function renderLargeShapes(shapes) { 1402 | shapes.forEach((shape) => { 1403 | const area = shape.getArea(); 1404 | shape.render(area); 1405 | }); 1406 | } 1407 | 1408 | const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; 1409 | renderLargeShapes(shapes); 1410 | ``` 1411 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1412 | 1413 | ### 接口隔离原则 (ISP) 1414 | 1415 | JavaScript 没有接口, 所以这个原则不像其它语言那么严格。 不过, 对于 JavaScript 这种缺少类 1416 | 型的语言来说, 它依然是重要并且有意义的。 1417 | 1418 | 接口隔离原则说的是 “客户端不应该强制依赖他们不需要的接口。” 在 JavaScript 这种弱类型语言中, 1419 | 接口是隐式的契约。 1420 | 1421 | 在 JavaScript 中能比较好的说明这个原则的是一个类需要一个巨大的配置对象。 不需要客户端去设置大 1422 | 量的选项是有益的, 因为多数情况下他们不需要全部的设置。 让它们变成可选的有助于防止出现一个“胖接 1423 | 口”。 1424 | 1425 | **不好的:** 1426 | ```javascript 1427 | class DOMTraverser { 1428 | constructor(settings) { 1429 | this.settings = settings; 1430 | this.setup(); 1431 | } 1432 | 1433 | setup() { 1434 | this.rootNode = this.settings.rootNode; 1435 | this.animationModule.setup(); 1436 | } 1437 | 1438 | traverse() { 1439 | // ... 1440 | } 1441 | } 1442 | 1443 | const $ = new DOMTraverser({ 1444 | rootNode: document.getElementsByTagName('body'), 1445 | animationModule() {} // Most of the time, we won't need to animate when traversing. 1446 | // ... 1447 | }); 1448 | 1449 | ``` 1450 | 1451 | **好的:** 1452 | ```javascript 1453 | class DOMTraverser { 1454 | constructor(settings) { 1455 | this.settings = settings; 1456 | this.options = settings.options; 1457 | this.setup(); 1458 | } 1459 | 1460 | setup() { 1461 | this.rootNode = this.settings.rootNode; 1462 | this.setupOptions(); 1463 | } 1464 | 1465 | setupOptions() { 1466 | if (this.options.animationModule) { 1467 | // ... 1468 | } 1469 | } 1470 | 1471 | traverse() { 1472 | // ... 1473 | } 1474 | } 1475 | 1476 | const $ = new DOMTraverser({ 1477 | rootNode: document.getElementsByTagName('body'), 1478 | options: { 1479 | animationModule() {} 1480 | } 1481 | }); 1482 | ``` 1483 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1484 | 1485 | ### 依赖反转原则 (DIP) 1486 | 1487 | 这个原则阐述了两个重要的事情: 1488 | 1489 | 1. 高级模块不应该依赖于低级模块, 两者都应该依赖与抽象; 1490 | 2. 抽象不应当依赖于具体实现, 具体实现应当依赖于抽象。 1491 | 1492 | 这个一开始会很难理解, 但是如果你使用过 Angular.js , 你应该已经看到过通过依赖注入来实现的这 1493 | 个原则, 虽然他们不是相同的概念, 依赖反转原则让高级模块远离低级模块的细节和创建, 可以通过 DI 1494 | 来实现。 这样做的巨大益处是降低模块间的耦合。 耦合是一个非常糟糕的开发模式, 因为会导致代码难于 1495 | 重构。 1496 | 1497 | 如上所述, JavaScript 没有接口, 所以被依赖的抽象是隐式契约。 也就是说, 一个对象/类的方法和 1498 | 属性直接暴露给另外一个对象/类。 在下面的例子中, 任何一个 Request 模块的隐式契约 `InventoryTracker` 1499 | 将有一个 `requestItems` 方法。 1500 | 1501 | **不好的:** 1502 | ```javascript 1503 | class InventoryRequester { 1504 | constructor() { 1505 | this.REQ_METHODS = ['HTTP']; 1506 | } 1507 | 1508 | requestItem(item) { 1509 | // ... 1510 | } 1511 | } 1512 | 1513 | class InventoryTracker { 1514 | constructor(items) { 1515 | this.items = items; 1516 | 1517 | // 不好的: 我们已经创建了一个对请求的具体实现的依赖, 我们只有一个 requestItems 方法依 1518 | // 赖一个请求方法 'request' 1519 | this.requester = new InventoryRequester(); 1520 | } 1521 | 1522 | requestItems() { 1523 | this.items.forEach((item) => { 1524 | this.requester.requestItem(item); 1525 | }); 1526 | } 1527 | } 1528 | 1529 | const inventoryTracker = new InventoryTracker(['apples', 'bananas']); 1530 | inventoryTracker.requestItems(); 1531 | ``` 1532 | 1533 | **好的:** 1534 | ```javascript 1535 | class InventoryTracker { 1536 | constructor(items, requester) { 1537 | this.items = items; 1538 | this.requester = requester; 1539 | } 1540 | 1541 | requestItems() { 1542 | this.items.forEach((item) => { 1543 | this.requester.requestItem(item); 1544 | }); 1545 | } 1546 | } 1547 | 1548 | class InventoryRequesterV1 { 1549 | constructor() { 1550 | this.REQ_METHODS = ['HTTP']; 1551 | } 1552 | 1553 | requestItem(item) { 1554 | // ... 1555 | } 1556 | } 1557 | 1558 | class InventoryRequesterV2 { 1559 | constructor() { 1560 | this.REQ_METHODS = ['WS']; 1561 | } 1562 | 1563 | requestItem(item) { 1564 | // ... 1565 | } 1566 | } 1567 | 1568 | // 通过外部创建依赖项并将它们注入, 我们可以轻松的用一个崭新的使用 WebSockets 的请求模块进行 1569 | // 替换。 1570 | const inventoryTracker = new InventoryTracker(['apples', 'bananas'], new InventoryRequesterV2()); 1571 | inventoryTracker.requestItems(); 1572 | ``` 1573 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1574 | 1575 | ## **测试** 1576 | 1577 | 测试比发布更加重要。 如果你没有测试或者测试不够充分, 每次发布时你就不能确认没有破坏任何事情。 1578 | 测试的量由你的团队决定, 但是拥有 100% 的覆盖率(包括所有的语句和分支)是你为什么能达到高度自信 1579 | 和内心的平静。 这意味着需要一个额外的伟大的测试框架, 也需要一个好的[覆盖率工具](http://gotwarlost.github.io/istanbul/)。 1580 | 1581 | 没有理由不写测试。 这里有[大量的优秀的 JS 测试框架](http://jstherightway.org/#testing-tools), 1582 | 选一个适合你的团队的即可。 当为团队选择了测试框架之后, 接下来的目标是为生产的每一个新的功能/模 1583 | 块编写测试。 如果你倾向于测试驱动开发(TDD), 那就太棒了, 但是要点是确认你在上线任何功能或者重 1584 | 构一个现有功能之前, 达到了需要的目标覆盖率。 1585 | 1586 | ### 一个测试一个概念 1587 | 1588 | **不好的:** 1589 | ```javascript 1590 | const assert = require('assert'); 1591 | 1592 | describe('MakeMomentJSGreatAgain', () => { 1593 | it('handles date boundaries', () => { 1594 | let date; 1595 | 1596 | date = new MakeMomentJSGreatAgain('1/1/2015'); 1597 | date.addDays(30); 1598 | date.shouldEqual('1/31/2015'); 1599 | 1600 | date = new MakeMomentJSGreatAgain('2/1/2016'); 1601 | date.addDays(28); 1602 | assert.equal('02/29/2016', date); 1603 | 1604 | date = new MakeMomentJSGreatAgain('2/1/2015'); 1605 | date.addDays(28); 1606 | assert.equal('03/01/2015', date); 1607 | }); 1608 | }); 1609 | ``` 1610 | 1611 | **好的:** 1612 | ```javascript 1613 | const assert = require('assert'); 1614 | 1615 | describe('MakeMomentJSGreatAgain', () => { 1616 | it('handles 30-day months', () => { 1617 | const date = new MakeMomentJSGreatAgain('1/1/2015'); 1618 | date.addDays(30); 1619 | date.shouldEqual('1/31/2015'); 1620 | }); 1621 | 1622 | it('handles leap year', () => { 1623 | const date = new MakeMomentJSGreatAgain('2/1/2016'); 1624 | date.addDays(28); 1625 | assert.equal('02/29/2016', date); 1626 | }); 1627 | 1628 | it('handles non-leap year', () => { 1629 | const date = new MakeMomentJSGreatAgain('2/1/2015'); 1630 | date.addDays(28); 1631 | assert.equal('03/01/2015', date); 1632 | }); 1633 | }); 1634 | ``` 1635 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1636 | 1637 | ## **并发** 1638 | 1639 | ### 使用 Promises, 不要使用回调 1640 | 1641 | 回调不够简洁, 因为他们会产生过多的嵌套。 在 ES2015/ES6 中, Promises 已经是内置的全局类型 1642 | 了,使用它们吧! 1643 | 1644 | **不好的:** 1645 | ```javascript 1646 | require('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => { 1647 | if (requestErr) { 1648 | console.error(requestErr); 1649 | } else { 1650 | require('fs').writeFile('article.html', response.body, (writeErr) => { 1651 | if (writeErr) { 1652 | console.error(writeErr); 1653 | } else { 1654 | console.log('File written'); 1655 | } 1656 | }); 1657 | } 1658 | }); 1659 | 1660 | ``` 1661 | 1662 | **好的:** 1663 | ```javascript 1664 | require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') 1665 | .then((response) => { 1666 | return require('fs-promise').writeFile('article.html', response); 1667 | }) 1668 | .then(() => { 1669 | console.log('File written'); 1670 | }) 1671 | .catch((err) => { 1672 | console.error(err); 1673 | }); 1674 | 1675 | ``` 1676 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1677 | 1678 | ### Async/Await 比 Promises 更加简洁 1679 | 1680 | Promises 是回调的一个非常简洁的替代品, 但是 ES2017/ES8 带来的 async 和 await 提供了一个 1681 | 更加简洁的解决方案。 你需要的只是一个前缀为 `async` 关键字的函数, 接下来就可以不需要 `then` 1682 | 函数链来编写逻辑了。 如果你能使用 ES2017/ES8 的高级功能的话, 今天就使用它吧! 1683 | 1684 | **不好的:** 1685 | ```javascript 1686 | require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') 1687 | .then((response) => { 1688 | return require('fs-promise').writeFile('article.html', response); 1689 | }) 1690 | .then(() => { 1691 | console.log('File written'); 1692 | }) 1693 | .catch((err) => { 1694 | console.error(err); 1695 | }); 1696 | 1697 | ``` 1698 | 1699 | **好的:** 1700 | ```javascript 1701 | async function getCleanCodeArticle() { 1702 | try { 1703 | const response = await require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin'); 1704 | await require('fs-promise').writeFile('article.html', response); 1705 | console.log('File written'); 1706 | } catch(err) { 1707 | console.error(err); 1708 | } 1709 | } 1710 | ``` 1711 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1712 | 1713 | 1714 | ## **错误处理** 1715 | 1716 | 抛出错误是一件好事情! 他们意味着当你的程序有错时运行时可以成功确认, 并且通过停止执行当前堆栈 1717 | 上的函数来让你知道, 结束当前进程(在 Node 中), 在控制台中用一个堆栈跟踪提示你。 1718 | 1719 | ### 不要忽略捕捉到的错误 1720 | 1721 | 对捕捉到的错误不做任何处理不能给你修复错误或者响应错误的能力。 向控制台记录错误 (`console.log`) 1722 | 也不怎么好, 因为往往会丢失在海量的控制台输出中。 如果你把任意一段代码用 `try/catch` 包装那就 1723 | 意味着你想到这里可能会错, 因此你应该有个修复计划, 或者当错误发生时有一个代码路径。 1724 | 1725 | **不好的:** 1726 | ```javascript 1727 | try { 1728 | functionThatMightThrow(); 1729 | } catch (error) { 1730 | console.log(error); 1731 | } 1732 | ``` 1733 | 1734 | **好的:** 1735 | ```javascript 1736 | try { 1737 | functionThatMightThrow(); 1738 | } catch (error) { 1739 | // One option (more noisy than console.log): 1740 | console.error(error); 1741 | // Another option: 1742 | notifyUserOfError(error); 1743 | // Another option: 1744 | reportErrorToService(error); 1745 | // OR do all three! 1746 | } 1747 | ``` 1748 | 1749 | ### 不要忽略被拒绝的 promise 1750 | 1751 | 与你不应忽略来自 `try/catch` 的错误的原因相同。 1752 | 1753 | **不好的:** 1754 | ```javascript 1755 | getdata() 1756 | .then((data) => { 1757 | functionThatMightThrow(data); 1758 | }) 1759 | .catch((error) => { 1760 | console.log(error); 1761 | }); 1762 | ``` 1763 | 1764 | **好的:** 1765 | ```javascript 1766 | getdata() 1767 | .then((data) => { 1768 | functionThatMightThrow(data); 1769 | }) 1770 | .catch((error) => { 1771 | // One option (more noisy than console.log): 1772 | console.error(error); 1773 | // Another option: 1774 | notifyUserOfError(error); 1775 | // Another option: 1776 | reportErrorToService(error); 1777 | // OR do all three! 1778 | }); 1779 | ``` 1780 | 1781 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1782 | 1783 | ## **格式化** 1784 | 1785 | 格式化是主观的。 就像其它规则一样, 没有必须让你遵守的硬性规则。 重点是不要因为格式去争论, 这 1786 | 里有[大量的工具](http://standardjs.com/rules.html)来自动格式化, 使用其中的一个即可! 因 1787 | 为做为工程师去争论格式化就是在浪费时间和金钱。 1788 | 1789 | 针对自动格式化工具不能涵盖的问题(缩进、 制表符还是空格、 双引号还是单引号等), 这里有一些指南。 1790 | 1791 | ### 使用一致的大小写 1792 | 1793 | JavaScript 是无类型的, 所以大小写告诉你关于你的变量、 函数等的很多事情。 这些规则是主观的, 1794 | 所以你的团队可以选择他们想要的。 重点是, 不管你们选择了什么, 要保持一致。 1795 | 1796 | **不好的:** 1797 | ```javascript 1798 | const DAYS_IN_WEEK = 7; 1799 | const daysInMonth = 30; 1800 | 1801 | const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 1802 | const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; 1803 | 1804 | function eraseDatabase() {} 1805 | function restore_database() {} 1806 | 1807 | class animal {} 1808 | class Alpaca {} 1809 | ``` 1810 | 1811 | **好的:** 1812 | ```javascript 1813 | const DAYS_IN_WEEK = 7; 1814 | const DAYS_IN_MONTH = 30; 1815 | 1816 | const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 1817 | const artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; 1818 | 1819 | function eraseDatabase() {} 1820 | function restoreDatabase() {} 1821 | 1822 | class Animal {} 1823 | class Alpaca {} 1824 | ``` 1825 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1826 | 1827 | 1828 | ### 函数的调用方与被调用方应该靠近 1829 | 1830 | 如果一个函数调用另一个, 则在代码中这两个函数的竖直位置应该靠近。 理想情况下,保持被调用函数在被 1831 | 调用函数的正上方。 我们倾向于从上到下阅读代码, 就像读一章报纸。 由于这个原因, 保持你的代码可 1832 | 以按照这种方式阅读。 1833 | 1834 | **不好的:** 1835 | ```javascript 1836 | class PerformanceReview { 1837 | constructor(employee) { 1838 | this.employee = employee; 1839 | } 1840 | 1841 | lookupPeers() { 1842 | return db.lookup(this.employee, 'peers'); 1843 | } 1844 | 1845 | lookupManager() { 1846 | return db.lookup(this.employee, 'manager'); 1847 | } 1848 | 1849 | getPeerReviews() { 1850 | const peers = this.lookupPeers(); 1851 | // ... 1852 | } 1853 | 1854 | perfReview() { 1855 | this.getPeerReviews(); 1856 | this.getManagerReview(); 1857 | this.getSelfReview(); 1858 | } 1859 | 1860 | getManagerReview() { 1861 | const manager = this.lookupManager(); 1862 | } 1863 | 1864 | getSelfReview() { 1865 | // ... 1866 | } 1867 | } 1868 | 1869 | const review = new PerformanceReview(user); 1870 | review.perfReview(); 1871 | ``` 1872 | 1873 | **好的:** 1874 | ```javascript 1875 | class PerformanceReview { 1876 | constructor(employee) { 1877 | this.employee = employee; 1878 | } 1879 | 1880 | perfReview() { 1881 | this.getPeerReviews(); 1882 | this.getManagerReview(); 1883 | this.getSelfReview(); 1884 | } 1885 | 1886 | getPeerReviews() { 1887 | const peers = this.lookupPeers(); 1888 | // ... 1889 | } 1890 | 1891 | lookupPeers() { 1892 | return db.lookup(this.employee, 'peers'); 1893 | } 1894 | 1895 | getManagerReview() { 1896 | const manager = this.lookupManager(); 1897 | } 1898 | 1899 | lookupManager() { 1900 | return db.lookup(this.employee, 'manager'); 1901 | } 1902 | 1903 | getSelfReview() { 1904 | // ... 1905 | } 1906 | } 1907 | 1908 | const review = new PerformanceReview(employee); 1909 | review.perfReview(); 1910 | ``` 1911 | 1912 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1913 | 1914 | ## **注释** 1915 | 1916 | ### 仅仅对包含复杂业务逻辑的东西进行注释 1917 | 1918 | 注释是代码的辩解, 不是要求。 多数情况下, 好的代码就是文档。 1919 | 1920 | **不好的:** 1921 | ```javascript 1922 | function hashIt(data) { 1923 | // The hash 1924 | let hash = 0; 1925 | 1926 | // Length of string 1927 | const length = data.length; 1928 | 1929 | // Loop through every character in data 1930 | for (let i = 0; i < length; i++) { 1931 | // Get character code. 1932 | const char = data.charCodeAt(i); 1933 | // Make the hash 1934 | hash = ((hash << 5) - hash) + char; 1935 | // Convert to 32-bit integer 1936 | hash &= hash; 1937 | } 1938 | } 1939 | ``` 1940 | 1941 | **好的:** 1942 | ```javascript 1943 | 1944 | function hashIt(data) { 1945 | let hash = 0; 1946 | const length = data.length; 1947 | 1948 | for (let i = 0; i < length; i++) { 1949 | const char = data.charCodeAt(i); 1950 | hash = ((hash << 5) - hash) + char; 1951 | 1952 | // Convert to 32-bit integer 1953 | hash &= hash; 1954 | } 1955 | } 1956 | 1957 | ``` 1958 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1959 | 1960 | ### 不要在代码库中保存注释掉的代码 1961 | 1962 | 因为有版本控制, 把旧的代码留在历史记录即可。 1963 | 1964 | **不好的:** 1965 | ```javascript 1966 | doStuff(); 1967 | // doOtherStuff(); 1968 | // doSomeMoreStuff(); 1969 | // doSoMuchStuff(); 1970 | ``` 1971 | 1972 | **好的:** 1973 | ```javascript 1974 | doStuff(); 1975 | ``` 1976 | **[⬆ 返回顶部](#代码整洁的-javascript)** 1977 | 1978 | ### 不要有日志式的注释 1979 | 1980 | 记住, 使用版本控制! 不需要僵尸代码, 注释掉的代码, 尤其是日志式的注释。 使用 `git log` 来 1981 | 获取历史记录。 1982 | 1983 | **不好的:** 1984 | ```javascript 1985 | /** 1986 | * 2016-12-20: Removed monads, didn't understand them (RM) 1987 | * 2016-10-01: Improved using special monads (JP) 1988 | * 2016-02-03: Removed type-checking (LI) 1989 | * 2015-03-14: Added combine with type-checking (JR) 1990 | */ 1991 | function combine(a, b) { 1992 | return a + b; 1993 | } 1994 | ``` 1995 | 1996 | **好的:** 1997 | ```javascript 1998 | function combine(a, b) { 1999 | return a + b; 2000 | } 2001 | ``` 2002 | **[⬆ 返回顶部](#代码整洁的-javascript)** 2003 | 2004 | ### 避免占位符 2005 | 2006 | 它们仅仅添加了干扰。 让函数和变量名称与合适的缩进和格式化为你的代码提供视觉结构。 2007 | 2008 | **不好的:** 2009 | ```javascript 2010 | //////////////////////////////////////////////////////////////////////////////// 2011 | // Scope Model Instantiation 2012 | //////////////////////////////////////////////////////////////////////////////// 2013 | $scope.model = { 2014 | menu: 'foo', 2015 | nav: 'bar' 2016 | }; 2017 | 2018 | //////////////////////////////////////////////////////////////////////////////// 2019 | // Action setup 2020 | //////////////////////////////////////////////////////////////////////////////// 2021 | const actions = function() { 2022 | // ... 2023 | }; 2024 | ``` 2025 | 2026 | **好的:** 2027 | ```javascript 2028 | $scope.model = { 2029 | menu: 'foo', 2030 | nav: 'bar' 2031 | }; 2032 | 2033 | const actions = function() { 2034 | // ... 2035 | }; 2036 | ``` 2037 | **[⬆ 返回顶部](#代码整洁的-javascript)** 2038 | 2039 | ## Translation 2040 | 2041 | This is also available in other languages: 2042 | 2043 | - ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [fesnt/clean-code-javascript](https://github.com/fesnt/clean-code-javascript) 2044 | - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese**: 2045 | - [alivebao/clean-code-js](https://github.com/alivebao/clean-code-js) 2046 | - [beginor/clean-code-js](https://github.com/beginor/clean-code-javascript/blob/master/README-zh-CN.md) 2047 | - ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [marcbruederlin/clean-code-javascript](https://github.com/marcbruederlin/clean-code-javascript) 2048 | - ![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [qkraudghgh/clean-code-javascript-ko](https://github.com/qkraudghgh/clean-code-javascript-ko) 2049 | - ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: 2050 | - [BoryaMogila/clean-code-javascript-ru/](https://github.com/BoryaMogila/clean-code-javascript-ru/) 2051 | - [maksugr/clean-code-javascript](https://github.com/maksugr/clean-code-javascript) 2052 | - ![vi](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnamese**: [hienvd/clean-code-javascript/](https://github.com/hienvd/clean-code-javascript/) 2053 | 2054 | **[⬆ 返回顶部](#代码整洁的-javascript)** 2055 | --------------------------------------------------------------------------------