代码整洁的 JavaScript

简介

clean-code-javaScript-中文版 - 图1

将源自 Robert C. Martin 的 Clean Code
的软件工程原则适配到 JavaScript 。 这不是一个代码风格指南, 它是一个使用 JavaScript 来生产
可读的, 可重用的, 以及可重构的软件的指南。

这里的每一项原则都不是必须遵守的, 甚至只有更少的能够被广泛认可。 这些仅仅是指南而已, 但是却是
Clean Code 作者多年经验的结晶。

我们的软件工程行业只有短短的 50 年, 依然有很多要我们去学习。 当软件架构与建筑架构一样古老时,
也许我们将会有硬性的规则去遵守。 而现在, 让这些指南做为你和你的团队生产的 JavaScript 代码的
质量的标准。

还有一件事: 知道这些指南并不能马上让你成为一个更加出色的软件开发者, 并且使用它们工作多年也并
不意味着你不再会犯错误。 每一段代码最开始都是草稿, 像湿粘土一样被打造成最终的形态。 最后当我们
和搭档们一起审查代码时清除那些不完善之处, 不要因为最初需要改善的草稿代码而自责, 而是对那些代
码下手。

变量

使用有意义并且可读的变量名称

不好的:

  1. const yyyymmdstr = moment().format('YYYY/MM/DD');

好的:

  1. const currentDate = moment().format('YYYY/MM/DD');

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

为相同类型的变量使用相同的词汇

不好的:

  1. getUserInfo();
  2. getClientData();
  3. getCustomerRecord();

好的:

  1. getUser();

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

使用可搜索的名称

我们要阅读的代码比要写的代码多得多, 所以我们写出的代码的可读性和可搜索性是很重要的。 使用没有
意义的变量名将会导致我们的程序难于理解, 将会伤害我们的读者, 所以请使用可搜索的变量名。 类似
buddy.jsESLint
的工具可以帮助我们找到未命名的常量。

不好的:

  1. // 艹, 86400000 是什么鬼?
  2. setTimeout(blastOff, 86400000);

好的:

  1. // 将它们声明为全局常量 `const` 。
  2. const MILLISECONDS_IN_A_DAY = 86400000;
  3. setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

使用解释性的变量

不好的:

  1. const address = 'One Infinite Loop, Cupertino 95014';
  2. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
  3. saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

好的:

  1. const address = 'One Infinite Loop, Cupertino 95014';
  2. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
  3. const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
  4. saveCityZipCode(city, zipCode);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免心理映射

显示比隐式更好

不好的:

  1. const locations = ['Austin', 'New York', 'San Francisco'];
  2. locations.forEach((l) => {
  3. doStuff();
  4. doSomeOtherStuff();
  5. // ...
  6. // ...
  7. // ...
  8. // 等等, `l` 是啥?
  9. dispatch(l);
  10. });

好的:

  1. const locations = ['Austin', 'New York', 'San Francisco'];
  2. locations.forEach((location) => {
  3. doStuff();
  4. doSomeOtherStuff();
  5. // ...
  6. // ...
  7. // ...
  8. dispatch(location);
  9. });

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

不添加不必要的上下文

如果你的类名/对象名有意义, 不要在变量名上再重复。

不好的:

  1. const Car = {
  2. carMake: 'Honda',
  3. carModel: 'Accord',
  4. carColor: 'Blue'
  5. };
  6. function paintCar(car) {
  7. car.carColor = 'Red';
  8. }

好的:

  1. const Car = {
  2. make: 'Honda',
  3. model: 'Accord',
  4. color: 'Blue'
  5. };
  6. function paintCar(car) {
  7. car.color = 'Red';
  8. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

使用默认变量替代短路运算或条件

不好的:

  1. function createMicrobrewery(name) {
  2. const breweryName = name || 'Hipster Brew Co.';
  3. // ...
  4. }

好的:

  1. function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
  2. // ...
  3. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

函数

函数参数 (两个以下最理想)

限制函数参数的个数是非常重要的, 因为这样将使你的函数容易进行测试。 一旦超过三个参数将会导致组
合爆炸, 因为你不得不编写大量针对每个参数的测试用例。

没有参数是最理想的, 一个或者两个参数也是可以的, 三个参数应该避免, 超过三个应该被重构。 通常,
如果你有一个超过两个函数的参数, 那就意味着你的函数尝试做太多的事情。 如果不是, 多数情况下一个
更高级对象可能会满足需求。

由于 JavaScript 允许我们不定义类型/模板就可以创建对象, 当你发现你自己需要大量的参数时, 你
可以使用一个对象。

不好的:

  1. function createMenu(title, body, buttonText, cancellable) {
  2. // ...
  3. }

好的:

  1. const menuConfig = {
  2. title: 'Foo',
  3. body: 'Bar',
  4. buttonText: 'Baz',
  5. cancellable: true
  6. };
  7. function createMenu(config) {
  8. // ...
  9. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

函数应当只做一件事情

这是软件工程中最重要的一条规则, 当函数需要做更多的事情时, 它们将会更难进行编写、 测试和推理。
当你能将一个函数隔离到只有一个动作, 他们将能够被容易的进行重构并且你的代码将会更容易阅读。 如
果你严格遵守本指南中的这一条, 你将会领先于许多开发者。

不好的:

  1. function emailClients(clients) {
  2. clients.forEach((client) => {
  3. const clientRecord = database.lookup(client);
  4. if (clientRecord.isActive()) {
  5. email(client);
  6. }
  7. });
  8. }

好的:

  1. function emailClients(clients) {
  2. clients
  3. .filter(isClientActive)
  4. .forEach(email);
  5. }
  6. function isClientActive(client) {
  7. const clientRecord = database.lookup(client);
  8. return clientRecord.isActive();
  9. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

函数名称应该说明它要做什么

不好的:

  1. function addToDate(date, month) {
  2. // ...
  3. }
  4. const date = new Date();
  5. // 很难从函数名看出加了什么
  6. addToDate(date, 1);

好的:

  1. function addMonthToDate(month, date) {
  2. // ...
  3. }
  4. const date = new Date();
  5. addMonthToDate(1, date);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

函数应该只有一个抽象级别

当在你的函数中有多于一个抽象级别时, 你的函数通常做了太多事情。 拆分函数将会提升重用性和测试性。

不好的:

  1. function parseBetterJSAlternative(code) {
  2. const REGEXES = [
  3. // ...
  4. ];
  5. const statements = code.split(' ');
  6. const tokens = [];
  7. REGEXES.forEach((REGEX) => {
  8. statements.forEach((statement) => {
  9. // ...
  10. });
  11. });
  12. const ast = [];
  13. tokens.forEach((token) => {
  14. // lex...
  15. });
  16. ast.forEach((node) => {
  17. // parse...
  18. });
  19. }

好的:

  1. function tokenize(code) {
  2. const REGEXES = [
  3. // ...
  4. ];
  5. const statements = code.split(' ');
  6. const tokens = [];
  7. REGEXES.forEach((REGEX) => {
  8. statements.forEach((statement) => {
  9. tokens.push( /* ... */ );
  10. });
  11. });
  12. return tokens;
  13. }
  14. function lexer(tokens) {
  15. const ast = [];
  16. tokens.forEach((token) => {
  17. ast.push( /* ... */ );
  18. });
  19. return ast;
  20. }
  21. function parseBetterJSAlternative(code) {
  22. const tokens = tokenize(code);
  23. const ast = lexer(tokens);
  24. ast.forEach((node) => {
  25. // parse...
  26. });
  27. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

移除冗余代码

竭尽你的全力去避免冗余代码。 冗余代码是不好的, 因为它意味着当你需要修改一些逻辑时会有多个地方
需要修改。

想象一下你在经营一家餐馆, 你需要记录所有的库存西红柿, 洋葱, 大蒜, 各种香料等等。 如果你有多
个记录列表, 当你用西红柿做一道菜时你得更新多个列表。 如果你只有一个列表, 就只有一个地方需要更
新!

你有冗余代码通常是因为你有两个或多个稍微不同的东西, 它们共享大部分, 但是它们的不同之处迫使你使
用两个或更多独立的函数来处理大部分相同的东西。 移除冗余代码意味着创建一个可以处理这些不同之处的
抽象的函数/模块/类。

让这个抽象正确是关键的, 这是为什么要你遵循 Classes 那一章的 SOLID 的原因。 不好的抽象比冗
余代码更差, 所以要谨慎行事。 既然已经这么说了, 如果你能够做出一个好的抽象, 才去做。 不要重复
你自己, 否则你会发现当你要修改一个东西时时刻需要修改多个地方。

不好的:

  1. function showDeveloperList(developers) {
  2. developers.forEach((developer) => {
  3. const expectedSalary = developer.calculateExpectedSalary();
  4. const experience = developer.getExperience();
  5. const githubLink = developer.getGithubLink();
  6. const data = {
  7. expectedSalary,
  8. experience,
  9. githubLink
  10. };
  11. render(data);
  12. });
  13. }
  14. function showManagerList(managers) {
  15. managers.forEach((manager) => {
  16. const expectedSalary = manager.calculateExpectedSalary();
  17. const experience = manager.getExperience();
  18. const portfolio = manager.getMBAProjects();
  19. const data = {
  20. expectedSalary,
  21. experience,
  22. portfolio
  23. };
  24. render(data);
  25. });
  26. }

好的:

  1. function showList(employees) {
  2. employees.forEach((employee) => {
  3. const expectedSalary = employee.calculateExpectedSalary();
  4. const experience = employee.getExperience();
  5. let portfolio = employee.getGithubLink();
  6. if (employee.type === 'manager') {
  7. portfolio = employee.getMBAProjects();
  8. }
  9. const data = {
  10. expectedSalary,
  11. experience,
  12. portfolio
  13. };
  14. render(data);
  15. });
  16. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

使用 Object.assign 设置默认对象

不好的:

  1. const menuConfig = {
  2. title: null,
  3. body: 'Bar',
  4. buttonText: null,
  5. cancellable: true
  6. };
  7. function createMenu(config) {
  8. config.title = config.title || 'Foo';
  9. config.body = config.body || 'Bar';
  10. config.buttonText = config.buttonText || 'Baz';
  11. config.cancellable = config.cancellable === undefined ? config.cancellable : true;
  12. }
  13. createMenu(menuConfig);

好的:

  1. const menuConfig = {
  2. title: 'Order',
  3. // User did not include 'body' key
  4. buttonText: 'Send',
  5. cancellable: true
  6. };
  7. function createMenu(config) {
  8. config = Object.assign({
  9. title: 'Foo',
  10. body: 'Bar',
  11. buttonText: 'Baz',
  12. cancellable: true
  13. }, config);
  14. // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  15. // ...
  16. }
  17. createMenu(menuConfig);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

不要使用标记位做为函数参数

标记位是告诉你的用户这个函数做了不只一件事情。 函数应该只做一件事情。 如果你的函数因为一个布尔值
出现不同的代码路径, 请拆分它们。

不好的:

  1. function createFile(name, temp) {
  2. if (temp) {
  3. fs.create(`./temp/${name}`);
  4. } else {
  5. fs.create(name);
  6. }
  7. }

好的:

  1. function createFile(name) {
  2. fs.create(name);
  3. }
  4. function createTempFile(name) {
  5. createFile(`./temp/${name}`);
  6. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免副作用

如果一个函数做了除接受一个值然后返回一个值或多个值之外的任何事情, 它将会产生副作用, 它可能是
写入一个文件, 修改一个全局变量, 或者意外的把你所有的钱连接到一个陌生人那里。

现在在你的程序中确实偶尔需要副作用, 就像上面的代码, 你也许需要写入到一个文件, 你需要做的是集
中化你要做的事情, 不要让多个函数或者类写入一个特定的文件, 用一个服务来实现它, 一个并且只有一
个。

重点是避免这些常见的易犯的错误, 比如在对象之间共享状态而不使用任何结构, 使用任何地方都可以写入
的可变的数据类型, 没有集中化导致副作用。 如果你能做到这些, 那么你将会比其它的码农大军更加幸福。

不好的:

  1. // Global variable referenced by following function.
  2. // 全局变量被下面的函数引用
  3. // If we had another function that used this name, now it'd be an array and it
  4. // could break it.
  5. // 如果我们有另一个函数使用这个 name , 现在它应该是一个数组, 这可能会出现错误。
  6. let name = 'Ryan McDermott';
  7. function splitIntoFirstAndLastName() {
  8. name = name.split(' ');
  9. }
  10. splitIntoFirstAndLastName();
  11. console.log(name); // ['Ryan', 'McDermott'];

好的:

  1. function splitIntoFirstAndLastName(name) {
  2. return name.split(' ');
  3. }
  4. const name = 'Ryan McDermott';
  5. const newName = splitIntoFirstAndLastName(name);
  6. console.log(name); // 'Ryan McDermott';
  7. console.log(newName); // ['Ryan', 'McDermott'];

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

不要写入全局函数

污染全局在 JavaScript 中是一个不好的做法, 因为你可能会和另外一个类库冲突, 你的 API 的用户
可能不够聪明, 直到他们得到在生产环境得到一个异常。 让我们来考虑这样一个例子: 假设你要扩展
JavaScript 的 原生 Array , 添加一个可以显示两个数组的不同之处的 diff 方法, 你可以在
Array.prototype 中写一个新的方法, 但是它可能会和尝试做相同事情的其它类库发生冲突。 如果有
另外一个类库仅仅使用 diff 方法来查找数组的第一个元素和最后一个元素之间的不同之处呢? 这就是
为什么使用 ES2015/ES6 的类是一个更好的做法的原因, 只要简单的扩展全局的 Array 即可。

不好的:

  1. Array.prototype.diff = function diff(comparisonArray) {
  2. const hash = new Set(comparisonArray);
  3. return this.filter(elem => !hash.has(elem));
  4. };

好的:

  1. class SuperArray extends Array {
  2. diff(comparisonArray) {
  3. const hash = new Set(comparisonArray);
  4. return this.filter(elem => !hash.has(elem));
  5. }
  6. }

函数式编程优于指令式编程

JavaScript 不是 Haskell 那种方式的函数式语言, 但是它有它的函数式风格。 函数式语言更加简洁
并且更容易进行测试, 当你可以使用函数式编程风格时请尽情使用。

不好的:

  1. const programmerOutput = [
  2. {
  3. name: 'Uncle Bobby',
  4. linesOfCode: 500
  5. }, {
  6. name: 'Suzie Q',
  7. linesOfCode: 1500
  8. }, {
  9. name: 'Jimmy Gosling',
  10. linesOfCode: 150
  11. }, {
  12. name: 'Gracie Hopper',
  13. linesOfCode: 1000
  14. }
  15. ];
  16. let totalOutput = 0;
  17. for (let i = 0; i < programmerOutput.length; i++) {
  18. totalOutput += programmerOutput[i].linesOfCode;
  19. }

好的:

  1. const programmerOutput = [
  2. {
  3. name: 'Uncle Bobby',
  4. linesOfCode: 500
  5. }, {
  6. name: 'Suzie Q',
  7. linesOfCode: 1500
  8. }, {
  9. name: 'Jimmy Gosling',
  10. linesOfCode: 150
  11. }, {
  12. name: 'Gracie Hopper',
  13. linesOfCode: 1000
  14. }
  15. ];
  16. const totalOutput = programmerOutput
  17. .map((programmer) => programmer.linesOfCode)
  18. .reduce((acc, linesOfCode) => acc + linesOfCode, 0);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

封装条件语句

不好的:

  1. if (fsm.state === 'fetching' && isEmpty(listNode)) {
  2. // ...
  3. }

好的:

  1. function shouldShowSpinner(fsm, listNode) {
  2. return fsm.state === 'fetching' && isEmpty(listNode);
  3. }
  4. if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
  5. // ...
  6. }

避免负面条件

不好的:

  1. function isDOMNodeNotPresent(node) {
  2. // ...
  3. }
  4. if (!isDOMNodeNotPresent(node)) {
  5. // ...
  6. }

好的:

  1. function isDOMNodePresent(node) {
  2. // ...
  3. }
  4. if (isDOMNodePresent(node)) {
  5. // ...
  6. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免条件语句

这看起来似乎是一个不可能的任务。 第一次听到这个时, 多数人会说: “没有 if 语句还能期望我干
啥呢”, 答案是多数情况下你可以使用多态来完成同样的任务。 第二个问题通常是 “好了, 那么做很棒,
但是我为什么想要那样做呢”, 答案是我们学到的上一条代码整洁之道的理念: 一个函数应当只做一件事情。
当你有使用 if 语句的类/函数是, 你在告诉你的用户你的函数做了不止一件事情。 记住: 只做一件
事情。

不好的:

  1. class Airplane {
  2. // ...
  3. getCruisingAltitude() {
  4. switch (this.type) {
  5. case '777':
  6. return this.getMaxAltitude() - this.getPassengerCount();
  7. case 'Air Force One':
  8. return this.getMaxAltitude();
  9. case 'Cessna':
  10. return this.getMaxAltitude() - this.getFuelExpenditure();
  11. }
  12. }
  13. }

好的:

  1. class Airplane {
  2. // ...
  3. }
  4. class Boeing777 extends Airplane {
  5. // ...
  6. getCruisingAltitude() {
  7. return this.getMaxAltitude() - this.getPassengerCount();
  8. }
  9. }
  10. class AirForceOne extends Airplane {
  11. // ...
  12. getCruisingAltitude() {
  13. return this.getMaxAltitude();
  14. }
  15. }
  16. class Cessna extends Airplane {
  17. // ...
  18. getCruisingAltitude() {
  19. return this.getMaxAltitude() - this.getFuelExpenditure();
  20. }
  21. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免类型检查 (part 1)

JavaScript 是无类型的, 这意味着你的函数能接受任何类型的参数。 但是有时又会被这种自由咬伤,
于是又尝试在你的函数中做类型检查。 有很多种方式来避免这个, 第一个要考虑的是一致的 API 。

不好的:

  1. function travelToTexas(vehicle) {
  2. if (vehicle instanceof Bicycle) {
  3. vehicle.peddle(this.currentLocation, new Location('texas'));
  4. } else if (vehicle instanceof Car) {
  5. vehicle.drive(this.currentLocation, new Location('texas'));
  6. }
  7. }

好的:

  1. function travelToTexas(vehicle) {
  2. vehicle.move(this.currentLocation, new Location('texas'));
  3. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免类型检查 (part 2)

如果你使用原始的字符串、 整数和数组, 并且你不能使用多态, 但是你依然感觉到有类型检查的需要,
你应该考虑使用 TypeScript 。 它是一个常规 JavaScript 的优秀的替代品, 因为它在标准的 JavaScript
语法之上为你提供静态类型。 对常规 JavaScript 做人工类型检查的问题是需要大量的冗词来仿造类型安
全而不缺失可读性。 保持你的 JavaScript 简洁, 编写良好的测试, 并有良好的代码审阅, 否则使用
TypeScript (就像我说的, 它是一个伟大的替代品)来完成这些。

不好的:

  1. function combine(val1, val2) {
  2. if (typeof val1 === 'number' && typeof val2 === 'number' ||
  3. typeof val1 === 'string' && typeof val2 === 'string') {
  4. return val1 + val2;
  5. }
  6. throw new Error('Must be of type String or Number');
  7. }

好的:

  1. function combine(val1, val2) {
  2. return val1 + val2;
  3. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

不要过度优化

现代化浏览器运行时在幕后做大量的优化, 在大多数的时间, 做优化就是在浪费你的时间。 这些是好的
资源
, 用来
查看那些地方需要优化。 为这些而优化, 直到他们被修正。

不好的:

  1. // On old browsers, each iteration with uncached `list.length` would be costly
  2. // because of `list.length` recomputation. In modern browsers, this is optimized.
  3. // 在旧的浏览器上, 每次循环 `list.length` 都没有被缓存, 会导致不必要的开销, 因为要重新计
  4. // 算 `list.length` 。 在现代化浏览器上, 这个已经被优化了。
  5. for (let i = 0, len = list.length; i < len; i++) {
  6. // ...
  7. }

好的:

  1. for (let i = 0; i < list.length; i++) {
  2. // ...
  3. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

移除僵尸代码

僵死代码和冗余代码同样糟糕。 没有理由在代码库中保存它。 如果它不会被调用, 就删掉它。 当你需要
它时, 它依然保存在版本历史记录中。

不好的:

  1. function oldRequestModule(url) {
  2. // ...
  3. }
  4. function newRequestModule(url) {
  5. // ...
  6. }
  7. const req = newRequestModule;
  8. inventoryTracker('apples', req, 'www.inventory-awesome.io');

好的:

  1. function newRequestModule(url) {
  2. // ...
  3. }
  4. const req = newRequestModule;
  5. inventoryTracker('apples', req, 'www.inventory-awesome.io');

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

对象和数据结构

使用 getters 和 setters

JavaScript 没有接口或类型, 所以坚持这个模式是非常困难的, 因为我们没有 publicprivate
关键字。 正因为如此, 使用 getters 和 setters 来访问对象上的数据比简单的在一个对象上查找属性
要好得多。 “为什么?” 你可能会问, 好吧, 原因请看下面的列表:

  • 当你想在获取一个对象属性的背后做更多的事情时, 你不需要在代码库中查找和修改每一处访问;
  • 使用 set 可以让添加验证变得容易;
  • 封装内部实现;
  • 使用 getting 和 setting 时, 容易添加日志和错误处理;
  • 继承这个类, 你可以重写默认功能;
  • 你可以延迟加载对象的属性, 比如说从服务器获取。

不好的:

  1. class BankAccount {
  2. constructor() {
  3. this.balance = 1000;
  4. }
  5. }
  6. const bankAccount = new BankAccount();
  7. // Buy shoes...
  8. bankAccount.balance -= 100;

好的:

  1. class BankAccount {
  2. constructor(balance = 1000) {
  3. this._balance = balance;
  4. }
  5. // It doesn't have to be prefixed with `get` or `set` to be a getter/setter
  6. set balance(amount) {
  7. if (verifyIfAmountCanBeSetted(amount)) {
  8. this._balance = amount;
  9. }
  10. }
  11. get balance() {
  12. return this._balance;
  13. }
  14. verifyIfAmountCanBeSetted(val) {
  15. // ...
  16. }
  17. }
  18. const bankAccount = new BankAccount();
  19. // Buy shoes...
  20. bankAccount.balance -= shoesPrice;
  21. // Get balance
  22. let balance = bankAccount.balance;

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

让对象拥有私有成员

这个可以通过闭包来实现(针对 ES5 或更低)。

不好的:

  1. const Employee = function(name) {
  2. this.name = name;
  3. };
  4. Employee.prototype.getName = function getName() {
  5. return this.name;
  6. };
  7. const employee = new Employee('John Doe');
  8. console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
  9. delete employee.name;
  10. console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

好的:

  1. const Employee = function (name) {
  2. this.getName = function getName() {
  3. return name;
  4. };
  5. };
  6. const employee = new Employee('John Doe');
  7. console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
  8. delete employee.name;
  9. console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

ES2015/ES6 类优先与 ES5 纯函数

很难为经典的 ES5 类创建可读的的继承、 构造和方法定义。 如果你需要继承(并且感到奇怪为啥你不需
要), 则优先用 ES2015/ES6的类。 不过, 短小的函数优先于类, 直到你发现你需要更大并且更复杂的
对象。

不好的:

  1. const Animal = function(age) {
  2. if (!(this instanceof Animal)) {
  3. throw new Error('Instantiate Animal with `new`');
  4. }
  5. this.age = age;
  6. };
  7. Animal.prototype.move = function move() {};
  8. const Mammal = function(age, furColor) {
  9. if (!(this instanceof Mammal)) {
  10. throw new Error('Instantiate Mammal with `new`');
  11. }
  12. Animal.call(this, age);
  13. this.furColor = furColor;
  14. };
  15. Mammal.prototype = Object.create(Animal.prototype);
  16. Mammal.prototype.constructor = Mammal;
  17. Mammal.prototype.liveBirth = function liveBirth() {};
  18. const Human = function(age, furColor, languageSpoken) {
  19. if (!(this instanceof Human)) {
  20. throw new Error('Instantiate Human with `new`');
  21. }
  22. Mammal.call(this, age, furColor);
  23. this.languageSpoken = languageSpoken;
  24. };
  25. Human.prototype = Object.create(Mammal.prototype);
  26. Human.prototype.constructor = Human;
  27. Human.prototype.speak = function speak() {};

好的:

  1. class Animal {
  2. constructor(age) {
  3. this.age = age;
  4. }
  5. move() { /* ... */ }
  6. }
  7. class Mammal extends Animal {
  8. constructor(age, furColor) {
  9. super(age);
  10. this.furColor = furColor;
  11. }
  12. liveBirth() { /* ... */ }
  13. }
  14. class Human extends Mammal {
  15. constructor(age, furColor, languageSpoken) {
  16. super(age, furColor);
  17. this.languageSpoken = languageSpoken;
  18. }
  19. speak() { /* ... */ }
  20. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

使用方法链

这个模式在 JavaScript 中是非常有用的, 并且你可以在许多类库比如 jQuery 和 Lodash 中见到。
它使你的代码变得富有表现力, 并减少啰嗦。 因为这个原因, 我说, 使用方法链然后再看看你的代码
会变得多么简洁。 在你的类/方法中, 简单的在每个方法的最后返回 this , 然后你就能把这个类的
其它方法链在一起。

不好的:

  1. class Car {
  2. constructor() {
  3. this.make = 'Honda';
  4. this.model = 'Accord';
  5. this.color = 'white';
  6. }
  7. setMake(make) {
  8. this.make = make;
  9. }
  10. setModel(model) {
  11. this.model = model;
  12. }
  13. setColor(color) {
  14. this.color = color;
  15. }
  16. save() {
  17. console.log(this.make, this.model, this.color);
  18. }
  19. }
  20. const car = new Car();
  21. car.setColor('pink');
  22. car.setMake('Ford');
  23. car.setModel('F-150');
  24. car.save();

好的:

  1. class Car {
  2. constructor() {
  3. this.make = 'Honda';
  4. this.model = 'Accord';
  5. this.color = 'white';
  6. }
  7. setMake(make) {
  8. this.make = make;
  9. // NOTE: Returning this for chaining
  10. return this;
  11. }
  12. setModel(model) {
  13. this.model = model;
  14. // NOTE: Returning this for chaining
  15. return this;
  16. }
  17. setColor(color) {
  18. this.color = color;
  19. // NOTE: Returning this for chaining
  20. return this;
  21. }
  22. save() {
  23. console.log(this.make, this.model, this.color);
  24. // NOTE: Returning this for chaining
  25. return this;
  26. }
  27. }
  28. const car = new Car()
  29. .setColor('pink')
  30. .setMake('Ford')
  31. .setModel('F-150')
  32. .save();

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

组合优先于继承

正如设计模式四人帮所述, 如果可能,
你应该优先使用组合而不是继承。 有许多好的理由去使用继承, 也有许多好的理由去使用组合。这个格言
的重点是, 如果你本能的观点是继承, 那么请想一下组合能否更好的为你的问题建模。 很多情况下它真的
可以。

那么你也许会这样想, “我什么时候改使用继承?” 这取决于你手上的问题, 不过这儿有一个像样的列表说
明什么时候继承比组合更好用:

  1. 你的继承表示”是一个”的关系而不是”有一个”的关系(人类->动物 vs 用户->用户详情);
  2. 你可以重用来自基类的代码(人可以像所有动物一样行动);
  3. 你想通过基类对子类进行全局的修改(改变所有动物行动时的热量消耗);

不好的:

  1. class Employee {
  2. constructor(name, email) {
  3. this.name = name;
  4. this.email = email;
  5. }
  6. // ...
  7. }
  8. // 不好是因为雇员“有”税率数据, EmployeeTaxData 不是一个 Employee 类型。
  9. class EmployeeTaxData extends Employee {
  10. constructor(ssn, salary) {
  11. super();
  12. this.ssn = ssn;
  13. this.salary = salary;
  14. }
  15. // ...
  16. }

好的:

  1. class EmployeeTaxData {
  2. constructor(ssn, salary) {
  3. this.ssn = ssn;
  4. this.salary = salary;
  5. }
  6. // ...
  7. }
  8. class Employee {
  9. constructor(name, email) {
  10. this.name = name;
  11. this.email = email;
  12. }
  13. setTaxData(ssn, salary) {
  14. this.taxData = new EmployeeTaxData(ssn, salary);
  15. }
  16. // ...
  17. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

SOLID

单一职责原则 (SRP)

正如代码整洁之道所述, “永远不要有超过一个理由来修改一个类”。 给一个类塞满许多功能, 就像你在航
班上只能带一个行李箱一样, 这样做的问题你的类不会有理想的内聚性, 将会有太多的理由来对它进行修改。
最小化需要修改一个类的次数时很重要的, 因为如果一个类拥有太多的功能, 一旦你修改它的一小部分,
将会很难弄清楚会对代码库中的其它模块造成什么影响。

不好的:

  1. class UserSettings {
  2. constructor(user) {
  3. this.user = user;
  4. }
  5. changeSettings(settings) {
  6. if (this.verifyCredentials()) {
  7. // ...
  8. }
  9. }
  10. verifyCredentials() {
  11. // ...
  12. }
  13. }

好的:

  1. class UserAuth {
  2. constructor(user) {
  3. this.user = user;
  4. }
  5. verifyCredentials() {
  6. // ...
  7. }
  8. }
  9. class UserSettings {
  10. constructor(user) {
  11. this.user = user;
  12. this.auth = new UserAuth(user);
  13. }
  14. changeSettings(settings) {
  15. if (this.auth.verifyCredentials()) {
  16. // ...
  17. }
  18. }
  19. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

开闭原则 (OCP)

Bertrand Meyer 说过, “软件实体 (类, 模块, 函数等) 应该为扩展开放, 但是为修改关闭。” 这
是什么意思呢? 这个原则基本上说明了你应该允许用户添加功能而不必修改现有的代码。

不好的:

  1. class AjaxAdapter extends Adapter {
  2. constructor() {
  3. super();
  4. this.name = 'ajaxAdapter';
  5. }
  6. }
  7. class NodeAdapter extends Adapter {
  8. constructor() {
  9. super();
  10. this.name = 'nodeAdapter';
  11. }
  12. }
  13. class HttpRequester {
  14. constructor(adapter) {
  15. this.adapter = adapter;
  16. }
  17. fetch(url) {
  18. if (this.adapter.name === 'ajaxAdapter') {
  19. return makeAjaxCall(url).then((response) => {
  20. // transform response and return
  21. });
  22. } else if (this.adapter.name === 'httpNodeAdapter') {
  23. return makeHttpCall(url).then((response) => {
  24. // transform response and return
  25. });
  26. }
  27. }
  28. }
  29. function makeAjaxCall(url) {
  30. // request and return promise
  31. }
  32. function makeHttpCall(url) {
  33. // request and return promise
  34. }

好的:

  1. class AjaxAdapter extends Adapter {
  2. constructor() {
  3. super();
  4. this.name = 'ajaxAdapter';
  5. }
  6. request(url) {
  7. // request and return promise
  8. }
  9. }
  10. class NodeAdapter extends Adapter {
  11. constructor() {
  12. super();
  13. this.name = 'nodeAdapter';
  14. }
  15. request(url) {
  16. // request and return promise
  17. }
  18. }
  19. class HttpRequester {
  20. constructor(adapter) {
  21. this.adapter = adapter;
  22. }
  23. fetch(url) {
  24. return this.adapter.request(url).then((response) => {
  25. // transform response and return
  26. });
  27. }
  28. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

里氏代换原则 (LSP)

这是针对一个非常简单的里面的一个恐怖意图, 它的正式定义是: “如果 S 是 T 的一个子类型, 那么类
型为 T 的对象可以被类型为 S 的对象替换(例如, 类型为 S 的对象可作为类型为 T 的替代品)儿不需
要修改目标程序的期望性质 (正确性、 任务执行性等)。” 这甚至是个恐怖的定义。

最好的解释是, 如果你又一个基类和一个子类, 那个基类和字类可以互换而不会产生不正确的结果。 这可
能还有有些疑惑, 让我们来看一下这个经典的正方形与矩形的例子。 从数学上说, 一个正方形是一个矩形,
但是你用 “is-a” 的关系用继承来实现, 你将很快遇到麻烦。

不好的:

  1. class Rectangle {
  2. constructor() {
  3. this.width = 0;
  4. this.height = 0;
  5. }
  6. setColor(color) {
  7. // ...
  8. }
  9. render(area) {
  10. // ...
  11. }
  12. setWidth(width) {
  13. this.width = width;
  14. }
  15. setHeight(height) {
  16. this.height = height;
  17. }
  18. getArea() {
  19. return this.width * this.height;
  20. }
  21. }
  22. class Square extends Rectangle {
  23. setWidth(width) {
  24. this.width = width;
  25. this.height = width;
  26. }
  27. setHeight(height) {
  28. this.width = height;
  29. this.height = height;
  30. }
  31. }
  32. function renderLargeRectangles(rectangles) {
  33. rectangles.forEach((rectangle) => {
  34. rectangle.setWidth(4);
  35. rectangle.setHeight(5);
  36. const area = rectangle.getArea(); // BAD: Will return 25 for Square. Should be 20.
  37. rectangle.render(area);
  38. });
  39. }
  40. const rectangles = [new Rectangle(), new Rectangle(), new Square()];
  41. renderLargeRectangles(rectangles);

好的:

  1. class Shape {
  2. setColor(color) {
  3. // ...
  4. }
  5. render(area) {
  6. // ...
  7. }
  8. }
  9. class Rectangle extends Shape {
  10. constructor(width, height) {
  11. super();
  12. this.width = width;
  13. this.height = height;
  14. }
  15. getArea() {
  16. return this.width * this.height;
  17. }
  18. }
  19. class Square extends Shape {
  20. constructor(length) {
  21. super();
  22. this.length = length;
  23. }
  24. getArea() {
  25. return this.length * this.length;
  26. }
  27. }
  28. function renderLargeShapes(shapes) {
  29. shapes.forEach((shape) => {
  30. const area = shape.getArea();
  31. shape.render(area);
  32. });
  33. }
  34. const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
  35. renderLargeShapes(shapes);

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

接口隔离原则 (ISP)

JavaScript 没有接口, 所以这个原则不想其它语言那么严格。 不过, 对于 JavaScript 这种缺少类
型的语言来说, 它依然是重要并且有意义的。

接口隔离原则说的是 “客户端不应该强制依赖他们不需要的接口。” 在 JavaScript 这种弱类型语言中,
接口是隐式的契约。

在 JavaScript 中能比较好的说明这个原则的是一个类需要一个巨大的配置对象。 不需要客户端去设置大
量的选项是有益的, 因为多数情况下他们不需要全部的设置。 让它们变成可选的有助于防止出现一个“胖接
口”。

不好的:

  1. class DOMTraverser {
  2. constructor(settings) {
  3. this.settings = settings;
  4. this.setup();
  5. }
  6. setup() {
  7. this.rootNode = this.settings.rootNode;
  8. this.animationModule.setup();
  9. }
  10. traverse() {
  11. // ...
  12. }
  13. }
  14. const $ = new DOMTraverser({
  15. rootNode: document.getElementsByTagName('body'),
  16. animationModule() {} // Most of the time, we won't need to animate when traversing.
  17. // ...
  18. });

好的:

  1. class DOMTraverser {
  2. constructor(settings) {
  3. this.settings = settings;
  4. this.options = settings.options;
  5. this.setup();
  6. }
  7. setup() {
  8. this.rootNode = this.settings.rootNode;
  9. this.setupOptions();
  10. }
  11. setupOptions() {
  12. if (this.options.animationModule) {
  13. // ...
  14. }
  15. }
  16. traverse() {
  17. // ...
  18. }
  19. }
  20. const $ = new DOMTraverser({
  21. rootNode: document.getElementsByTagName('body'),
  22. options: {
  23. animationModule() {}
  24. }
  25. });

依赖反转原则 (DIP)

这个原则阐述了两个重要的事情:

  1. 高级模块不应该依赖于低级模块, 两者都应该依赖与抽象;
  2. 抽象不应当依赖于具体实现, 具体实现应当依赖于抽象。

这个一开始会很难理解, 但是如果你使用过 Angular.js , 你应该已经看到过通过依赖注入来实现的这
个原则, 虽然他们不是相同的概念, 依赖反转原则让高级模块远离低级模块的细节和创建, 可以通过 DI
来实现。 这样做的巨大益处是降低模块间的耦合。 耦合是一个非常糟糕的开发模式, 因为会导致代码难于
重构。

如上所述, JavaScript 没有接口, 所以被依赖的抽象是隐式契约。 也就是说, 一个对象/类的方法和
属性直接暴露给另外一个对象/类。 在下面的例子中, 任何一个 Request 模块的隐式契约 InventoryTracker
将有一个 requestItems 方法。

不好的:

  1. class InventoryRequester {
  2. constructor() {
  3. this.REQ_METHODS = ['HTTP'];
  4. }
  5. requestItem(item) {
  6. // ...
  7. }
  8. }
  9. class InventoryTracker {
  10. constructor(items) {
  11. this.items = items;
  12. // 不好的: 我们已经创建了一个对请求的具体实现的依赖, 我们只有一个 requestItems 方法依
  13. // 赖一个请求方法 'request'
  14. this.requester = new InventoryRequester();
  15. }
  16. requestItems() {
  17. this.items.forEach((item) => {
  18. this.requester.requestItem(item);
  19. });
  20. }
  21. }
  22. const inventoryTracker = new InventoryTracker(['apples', 'bananas']);
  23. inventoryTracker.requestItems();

好的:

  1. class InventoryTracker {
  2. constructor(items, requester) {
  3. this.items = items;
  4. this.requester = requester;
  5. }
  6. requestItems() {
  7. this.items.forEach((item) => {
  8. this.requester.requestItem(item);
  9. });
  10. }
  11. }
  12. class InventoryRequesterV1 {
  13. constructor() {
  14. this.REQ_METHODS = ['HTTP'];
  15. }
  16. requestItem(item) {
  17. // ...
  18. }
  19. }
  20. class InventoryRequesterV2 {
  21. constructor() {
  22. this.REQ_METHODS = ['WS'];
  23. }
  24. requestItem(item) {
  25. // ...
  26. }
  27. }
  28. // 通过外部创建依赖项并将它们注入, 我们可以轻松的用一个崭新的使用 WebSockets 的请求模块进行
  29. // 替换。
  30. const inventoryTracker = new InventoryTracker(['apples', 'bananas'], new InventoryRequesterV2());
  31. inventoryTracker.requestItems();

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

测试

测试比发布更加重要。 如果你没有测试或者测试不够充分, 每次发布时你就不能确认没有破坏任何事情。
测试的量由你的团队决定, 但是拥有 100% 的覆盖率(包括所有的语句和分支)是你为什么能达到高度自信
和内心的平静。 这意味着需要一个额外的伟大的测试框架, 也需要一个好的覆盖率工具

没有理由不写测试。 这里有大量的优秀的 JS 测试框架
选一个适合你的团队的即可。 当为团队选择了测试框架之后, 接下来的目标是为生产的每一个新的功能/模
块编写测试。 如果你倾向于测试驱动开发(TDD), 那就太棒了, 但是要点是确认你在上线任何功能或者重
构一个现有功能之前, 达到了需要的目标覆盖率。

一个测试一个概念

不好的:

  1. const assert = require('assert');
  2. describe('MakeMomentJSGreatAgain', () => {
  3. it('handles date boundaries', () => {
  4. let date;
  5. date = new MakeMomentJSGreatAgain('1/1/2015');
  6. date.addDays(30);
  7. date.shouldEqual('1/31/2015');
  8. date = new MakeMomentJSGreatAgain('2/1/2016');
  9. date.addDays(28);
  10. assert.equal('02/29/2016', date);
  11. date = new MakeMomentJSGreatAgain('2/1/2015');
  12. date.addDays(28);
  13. assert.equal('03/01/2015', date);
  14. });
  15. });

好的:

  1. const assert = require('assert');
  2. describe('MakeMomentJSGreatAgain', () => {
  3. it('handles 30-day months', () => {
  4. const date = new MakeMomentJSGreatAgain('1/1/2015');
  5. date.addDays(30);
  6. date.shouldEqual('1/31/2015');
  7. });
  8. it('handles leap year', () => {
  9. const date = new MakeMomentJSGreatAgain('2/1/2016');
  10. date.addDays(28);
  11. assert.equal('02/29/2016', date);
  12. });
  13. it('handles non-leap year', () => {
  14. const date = new MakeMomentJSGreatAgain('2/1/2015');
  15. date.addDays(28);
  16. assert.equal('03/01/2015', date);
  17. });
  18. });

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

并发

使用 Promises, 不要使用回调

回调不够简洁, 因为他们会产生过多的嵌套。 在 ES2015/ES6 中, Promises 已经是内置的全局类型
了,使用它们吧!

不好的:

  1. require('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => {
  2. if (requestErr) {
  3. console.error(requestErr);
  4. } else {
  5. require('fs').writeFile('article.html', response.body, (writeErr) => {
  6. if (writeErr) {
  7. console.error(writeErr);
  8. } else {
  9. console.log('File written');
  10. }
  11. });
  12. }
  13. });

好的:

  1. require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
  2. .then((response) => {
  3. return require('fs-promise').writeFile('article.html', response);
  4. })
  5. .then(() => {
  6. console.log('File written');
  7. })
  8. .catch((err) => {
  9. console.error(err);
  10. });

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

Async/Await 比 Promises 更加简洁

Promises 是回调的一个非常简洁的替代品, 但是 ES2017/ES8 带来的 async 和 await 提供了一个
更加简洁的解决方案。 你需要的只是一个前缀为 async 关键字的函数, 接下来就可以不需要 then
函数链来编写逻辑了。 如果你能使用 ES2017/ES8 的高级功能的话, 今天就使用它吧!

不好的:

  1. require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
  2. .then((response) => {
  3. return require('fs-promise').writeFile('article.html', response);
  4. })
  5. .then(() => {
  6. console.log('File written');
  7. })
  8. .catch((err) => {
  9. console.error(err);
  10. });

好的:

  1. async function getCleanCodeArticle() {
  2. try {
  3. const response = await require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
  4. await require('fs-promise').writeFile('article.html', response);
  5. console.log('File written');
  6. } catch(err) {
  7. console.error(err);
  8. }
  9. }

错误处理

抛出错误是一件好事情! 他们意味着当你的程序有错时运行时可以成功确认, 并且通过停止执行当前堆栈
上的函数来让你知道, 结束当前进程(在 Node 中), 在控制台中用一个堆栈跟踪提示你。

不要忽略捕捉到的错误

对捕捉到的错误不做任何处理不能给你修复错误或者响应错误的能力。 向控制台记录错误 (console.log)
也不怎么好, 因为往往会丢失在海量的控制台输出中。 如果你把任意一段代码用 try/catch 包装那就
意味着你想到这里可能会错, 因此你应该有个修复计划, 或者当错误发生时有一个代码路径。

不好的:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. console.log(error);
  5. }

好的:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. // One option (more noisy than console.log):
  5. console.error(error);
  6. // Another option:
  7. notifyUserOfError(error);
  8. // Another option:
  9. reportErrorToService(error);
  10. // OR do all three!
  11. }

不要忽略被拒绝的 promise

与你不应忽略来自 try/catch 的错误的原因相同。

不好的:

  1. getdata()
  2. .then((data) => {
  3. functionThatMightThrow(data);
  4. })
  5. .catch((error) => {
  6. console.log(error);
  7. });

好的:

  1. getdata()
  2. .then((data) => {
  3. functionThatMightThrow(data);
  4. })
  5. .catch((error) => {
  6. // One option (more noisy than console.log):
  7. console.error(error);
  8. // Another option:
  9. notifyUserOfError(error);
  10. // Another option:
  11. reportErrorToService(error);
  12. // OR do all three!
  13. });

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

格式化

格式化是主观的。 就像其它规则一样, 没有必须让你遵守的硬性规则。 重点是不要因为格式去争论, 这
里有大量的工具来自动格式化, 使用其中的一个即可! 因
为做为工程师去争论格式化就是在浪费时间和金钱。

针对自动格式化工具不能涵盖的问题(缩进、 制表符还是空格、 双引号还是单引号等), 这里有一些指南。

使用一致的大小写

JavaScript 是无类型的, 所以大小写告诉你关于你的变量、 函数等的很多事情。 这些规则是主观的,
所以你的团队可以选择他们想要的。 重点是, 不管你们选择了什么, 要保持一致。

不好的:

  1. const DAYS_IN_WEEK = 7;
  2. const daysInMonth = 30;
  3. const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
  4. const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];
  5. function eraseDatabase() {}
  6. function restore_database() {}
  7. class animal {}
  8. class Alpaca {}

好的:

  1. const DAYS_IN_WEEK = 7;
  2. const DAYS_IN_MONTH = 30;
  3. const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
  4. const artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];
  5. function eraseDatabase() {}
  6. function restoreDatabase() {}
  7. class Animal {}
  8. class Alpaca {}

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

函数的调用方与被调用方应该靠近

如果一个函数调用另一个, 则在代码中这两个函数的竖直位置应该靠近。 理想情况下,保持被调用函数在被
调用函数的正上方。 我们倾向于从上到下阅读代码, 就像读一章报纸。 由于这个原因, 保持你的代码可
以按照这种方式阅读。

不好的:

  1. class PerformanceReview {
  2. constructor(employee) {
  3. this.employee = employee;
  4. }
  5. lookupPeers() {
  6. return db.lookup(this.employee, 'peers');
  7. }
  8. lookupManager() {
  9. return db.lookup(this.employee, 'manager');
  10. }
  11. getPeerReviews() {
  12. const peers = this.lookupPeers();
  13. // ...
  14. }
  15. perfReview() {
  16. this.getPeerReviews();
  17. this.getManagerReview();
  18. this.getSelfReview();
  19. }
  20. getManagerReview() {
  21. const manager = this.lookupManager();
  22. }
  23. getSelfReview() {
  24. // ...
  25. }
  26. }
  27. const review = new PerformanceReview(user);
  28. review.perfReview();

好的:

  1. class PerformanceReview {
  2. constructor(employee) {
  3. this.employee = employee;
  4. }
  5. perfReview() {
  6. this.getPeerReviews();
  7. this.getManagerReview();
  8. this.getSelfReview();
  9. }
  10. getPeerReviews() {
  11. const peers = this.lookupPeers();
  12. // ...
  13. }
  14. lookupPeers() {
  15. return db.lookup(this.employee, 'peers');
  16. }
  17. getManagerReview() {
  18. const manager = this.lookupManager();
  19. }
  20. lookupManager() {
  21. return db.lookup(this.employee, 'manager');
  22. }
  23. getSelfReview() {
  24. // ...
  25. }
  26. }
  27. const review = new PerformanceReview(employee);
  28. review.perfReview();

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

注释

仅仅对包含复杂业务逻辑的东西进行注释

注释是代码的辩解, 不是要求。 多数情况下, 好的代码就是文档。

不好的:

  1. function hashIt(data) {
  2. // The hash
  3. let hash = 0;
  4. // Length of string
  5. const length = data.length;
  6. // Loop through every character in data
  7. for (let i = 0; i < length; i++) {
  8. // Get character code.
  9. const char = data.charCodeAt(i);
  10. // Make the hash
  11. hash = ((hash << 5) - hash) + char;
  12. // Convert to 32-bit integer
  13. hash &= hash;
  14. }
  15. }

好的:

  1. function hashIt(data) {
  2. let hash = 0;
  3. const length = data.length;
  4. for (let i = 0; i < length; i++) {
  5. const char = data.charCodeAt(i);
  6. hash = ((hash << 5) - hash) + char;
  7. // Convert to 32-bit integer
  8. hash &= hash;
  9. }
  10. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

不要在代码库中保存注释掉的代码

因为有版本控制, 把旧的代码留在历史记录即可。

不好的:

  1. doStuff();
  2. // doOtherStuff();
  3. // doSomeMoreStuff();
  4. // doSoMuchStuff();

好的:

  1. doStuff();

不要有日志式的注释

记住, 使用版本控制! 不需要僵尸代码, 注释掉的代码, 尤其是日志式的注释。 使用 git log
获取历史记录。

不好的:

  1. /**
  2. * 2016-12-20: Removed monads, didn't understand them (RM)
  3. * 2016-10-01: Improved using special monads (JP)
  4. * 2016-02-03: Removed type-checking (LI)
  5. * 2015-03-14: Added combine with type-checking (JR)
  6. */
  7. function combine(a, b) {
  8. return a + b;
  9. }

好的:

  1. function combine(a, b) {
  2. return a + b;
  3. }

[

](#%E4%BB%A3%E7%A0%81%E6%95%B4%E6%B4%81%E7%9A%84-javascript)

避免占位符

它们仅仅添加了干扰。 让函数和变量名称与合适的缩进和格式化为你的代码提供视觉结构。

不好的:

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Scope Model Instantiation
  3. ////////////////////////////////////////////////////////////////////////////////
  4. $scope.model = {
  5. menu: 'foo',
  6. nav: 'bar'
  7. };
  8. ////////////////////////////////////////////////////////////////////////////////
  9. // Action setup
  10. ////////////////////////////////////////////////////////////////////////////////
  11. const actions = function() {
  12. // ...
  13. };

好的:

  1. $scope.model = {
  2. menu: 'foo',
  3. nav: 'bar'
  4. };
  5. const actions = function() {
  6. // ...
  7. };