测试代码质量的唯一方式:别人看你代码时说 f * k 的次数。
代码质量与其整洁度成正比。干净的代码,既在质量上较为可靠,也为后期维护、升级奠定了良好基础。
本文并不是代码风格指南,而是关于代码的可读性、复用性、扩展性探讨。
我们将从几个方面展开讨论:

  1. 变量
  2. 函数
  3. 对象和数据结构
  4. 类
  5. SOLID
  6. 测试
  7. 异步
  8. 错误处理
  9. 代码风格
  10. 注释

    变量

    用有意义且常用的单词命名变量

    Bad:
    1. const yyyymmdstr = moment().format('YYYY/MM/DD');
    2. 复制代码
    Good:
    1. const currentDate = moment().format('YYYY/MM/DD');
    2. 复制代码

保持统一

可能同一个项目对于获取用户信息,会有三个不一样的命名。应该保持统一,如果你不知道该如何取名,可以去 codelf 搜索,看别人是怎么取名的。
Bad:

  1. getUserInfo();
  2. getClientData();
  3. getCustomerRecord();
  4. 复制代码

Good:

  1. getUser()
  2. 复制代码

每个常量都该命名

可以用 buddy.js 或者 ESLint 检测代码中未命名的常量。
Bad:

  1. // 三个月之后你还能知道 86400000 是什么吗?
  2. setTimeout(blastOff, 86400000);
  3. 复制代码

Good:

  1. const MILLISECOND_IN_A_DAY = 86400000;
  2. setTimeout(blastOff, MILLISECOND_IN_A_DAY);
  3. 复制代码

可描述

通过一个变量生成了一个新变量,也需要为这个新变量命名,也就是说每个变量当你看到他第一眼你就知道他是干什么的。
Bad:

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

Good:

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

直接了当

Bad:

  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. });
  11. 复制代码

Good:

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

避免无意义的前缀

如果创建了一个对象 car,就没有必要把它的颜色命名为 carColor。
Bad:

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

Good:

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

使用默认值

Bad:

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

Good:

  1. function createMicrobrewery(name = 'Hipster Brew Co.') {
  2. // ...
  3. }
  4. 复制代码

函数

参数越少越好

如果参数超过两个,使用 ES2015/ES6 的解构语法,不用考虑参数的顺序。
Bad:

  1. function createMenu(title, body, buttonText, cancellable) {
  2. // ...
  3. }
  4. 复制代码

Good:

  1. function createMenu({ title, body, buttonText, cancellable }) {
  2. // ...
  3. }
  4. createMenu({
  5. title: 'Foo',
  6. body: 'Bar',
  7. buttonText: 'Baz',
  8. cancellable: true
  9. });
  10. 复制代码

只做一件事情

这是一条在软件工程领域流传久远的规则。严格遵守这条规则会让你的代码可读性更好,也更容易重构。如果违反这个规则,那么代码会很难被测试或者重用。
Bad:

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

Good:

  1. function emailActiveClients(clients) {
  2. clients
  3. .filter(isActiveClient)
  4. .forEach(email);
  5. }
  6. function isActiveClient() {
  7. const clientRecord = database.lookup(client);
  8. return clientRecord.isActive();
  9. }
  10. 复制代码

顾名思义

看函数名就应该知道它是干啥的。
Bad:

  1. function addToDate(date, month) {
  2. // ...
  3. }
  4. const date = new Date();
  5. // 很难知道是把什么加到日期中
  6. addToDate(date, 1);
  7. 复制代码

Good:

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

只需要一层抽象层

如果函数嵌套过多会导致很难复用以及测试。
Bad:

  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. }
  20. 复制代码

Good:

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

删除重复代码

很多时候虽然是同一个功能,但由于一两个不同点,让你不得不写两个几乎相同的函数。
要想优化重复代码需要有较强的抽象能力,错误的抽象还不如重复代码。所以在抽象过程中必须要遵循 SOLID 原则(SOLID 是什么?稍后会详细介绍)。
Bad:

  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. }
  27. 复制代码

Good:

  1. function showEmployeeList(employees) {
  2. employees.forEach(employee => {
  3. const expectedSalary = employee.calculateExpectedSalary();
  4. const experience = employee.getExperience();
  5. const data = {
  6. expectedSalary,
  7. experience,
  8. };
  9. switch(employee.type) {
  10. case 'develop':
  11. data.githubLink = employee.getGithubLink();
  12. break
  13. case 'manager':
  14. data.portfolio = employee.getMBAProjects();
  15. break
  16. }
  17. render(data);
  18. })
  19. }
  20. 复制代码

对象设置默认属性

Bad:

  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);
  14. 复制代码

Good:

  1. const menuConfig = {
  2. title: 'Order',
  3. // '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 就变成了: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  15. // ...
  16. }
  17. createMenu(menuConfig);
  18. 复制代码

不要传 flag 参数

通过 flag 的 true 或 false,来判断执行逻辑,违反了一个函数干一件事的原则。
Bad:

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

Good:

  1. function createFile(name) {
  2. fs.create(name);
  3. }
  4. function createFileTemplate(name) {
  5. createFile(`./temp/${name}`)
  6. }
  7. 复制代码

避免副作用(第一部分)

函数接收一个值返回一个新值,除此之外的行为我们都称之为副作用,比如修改全局变量、对文件进行 IO 操作等。
当函数确实需要副作用时,比如对文件进行 IO 操作时,请不要用多个函数/类进行文件操作,有且仅用一个函数/类来处理。也就是说副作用需要在唯一的地方处理。
副作用的三大天坑:随意修改可变数据类型、随意分享没有数据结构的状态、没有在统一地方处理副作用。
Bad:

  1. // 全局变量被一个函数引用
  2. // 现在这个变量从字符串变成了数组,如果有其他的函数引用,会发生无法预见的错误。
  3. var name = 'Ryan McDermott';
  4. function splitIntoFirstAndLastName() {
  5. name = name.split(' ');
  6. }
  7. splitIntoFirstAndLastName();
  8. console.log(name); // ['Ryan', 'McDermott'];
  9. 复制代码

Good:

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

避免副作用(第二部分)

在 JavaScript 中,基本类型通过赋值传递,对象和数组通过引用传递。以引用传递为例:
假如我们写一个购物车,通过 addItemToCart() 方法添加商品到购物车,修改 购物车数组。此时调用 purchase() 方法购买,由于引用传递,获取的 购物车数组 正好是最新的数据。
看起来没问题对不对?
如果当用户点击购买时,网络出现故障, purchase() 方法一直在重复调用,与此同时用户又添加了新的商品,这时网络又恢复了。那么 purchase() 方法获取到 购物车数组 就是错误的。
为了避免这种问题,我们需要在每次新增商品时,克隆 购物车数组 并返回新的数组。
Bad:

  1. const addItemToCart = (cart, item) => {
  2. cart.push({ item, date: Date.now() });
  3. };
  4. 复制代码

Good:

  1. const addItemToCart = (cart, item) => {
  2. return [...cart, {item, date: Date.now()}]
  3. };
  4. 复制代码

不要写全局方法

在 JavaScript 中,永远不要污染全局,会在生产环境中产生难以预料的 bug。举个例子,比如你在 Array.prototype 上新增一个 diff 方法来判断两个数组的不同。而你同事也打算做类似的事情,不过他的 diff 方法是用来判断两个数组首位元素的不同。很明显你们方法会产生冲突,遇到这类问题我们可以用 ES2015/ES6 的语法来对 Array 进行扩展。
Bad:

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

Good:

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

比起命令式我更喜欢函数式编程

函数式变编程可以让代码的逻辑更清晰更优雅,方便测试。
Bad:

  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. }
  20. 复制代码

Good:

  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 = programmerOutput
  17. .map(output => output.linesOfCode)
  18. .reduce((totalLines, lines) => totalLines + lines, 0)
  19. 复制代码

封装条件语句

Bad:

  1. if (fsm.state === 'fetching' && isEmpty(listNode)) {
  2. // ...
  3. }
  4. 复制代码

Good:

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

尽量别用“非”条件句

Bad:

  1. function isDOMNodeNotPresent(node) {
  2. // ...
  3. }
  4. if (!isDOMNodeNotPresent(node)) {
  5. // ...
  6. }
  7. 复制代码

Good:

  1. function isDOMNodePresent(node) {
  2. // ...
  3. }
  4. if (isDOMNodePresent(node)) {
  5. // ...
  6. }
  7. 复制代码

避免使用条件语句

Q:不用条件语句写代码是不可能的。
A:绝大多数场景可以用多态替代。
Q:用多态可行,但为什么就不能用条件语句了呢?
A:为了让代码更简洁易读,如果你的函数中出现了条件判断,那么说明你的函数不止干了一件事情,违反了函数单一原则。
Bad:

  1. class Airplane {
  2. // ...
  3. // 获取巡航高度
  4. getCruisingAltitude() {
  5. switch (this.type) {
  6. case '777':
  7. return this.getMaxAltitude() - this.getPassengerCount();
  8. case 'Air Force One':
  9. return this.getMaxAltitude();
  10. case 'Cessna':
  11. return this.getMaxAltitude() - this.getFuelExpenditure();
  12. }
  13. }
  14. }
  15. 复制代码

Good:

  1. class Airplane {
  2. // ...
  3. }
  4. // 波音777
  5. class Boeing777 extends Airplane {
  6. // ...
  7. getCruisingAltitude() {
  8. return this.getMaxAltitude() - this.getPassengerCount();
  9. }
  10. }
  11. // 空军一号
  12. class AirForceOne extends Airplane {
  13. // ...
  14. getCruisingAltitude() {
  15. return this.getMaxAltitude();
  16. }
  17. }
  18. // 赛纳斯飞机
  19. class Cessna extends Airplane {
  20. // ...
  21. getCruisingAltitude() {
  22. return this.getMaxAltitude() - this.getFuelExpenditure();
  23. }
  24. }
  25. 复制代码

避免类型检查(第一部分)

JavaScript 是无类型的,意味着你可以传任意类型参数,这种自由度很容易让人困扰,不自觉的就会去检查类型。仔细想想是你真的需要检查类型还是你的 API 设计有问题?
Bad:

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

Good:

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

避免类型检查(第二部分)

如果你需要做静态类型检查,比如字符串、整数等,推荐使用 TypeScript,不然你的代码会变得又臭又长。
Bad:

  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. }
  8. 复制代码

Good:

  1. function combine(val1, val2) {
  2. return val1 + val2;
  3. }
  4. 复制代码

不要过度优化

现代浏览器已经在底层做了很多优化,过去的很多优化方案都是无效的,会浪费你的时间,想知道现代浏览器优化了哪些内容,请点这里。
Bad:

  1. // 在老的浏览器中,由于 `list.length` 没有做缓存,每次迭代都会去计算,造成不必要开销。
  2. // 现代浏览器已对此做了优化。
  3. for (let i = 0, len = list.length; i < len; i++) {
  4. // ...
  5. }
  6. 复制代码

Good:

  1. for (let i = 0; i < list.length; i++) {
  2. // ...
  3. }
  4. 复制代码

删除弃用代码

很多时候有些代码已经没有用了,但担心以后会用,舍不得删。
如果你忘了这件事,这些代码就永远存在那里了。
放心删吧,你可以在代码库历史版本中找他它。
Bad:

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

Good:

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

对象和数据结构

用 get、set 方法操作数据

这样做可以带来很多好处,比如在操作数据时打日志,方便跟踪错误;在 set 的时候很容易对数据进行校验…
Bad:

  1. function makeBankAccount() {
  2. // ...
  3. return {
  4. balance: 0,
  5. // ...
  6. };
  7. }
  8. const account = makeBankAccount();
  9. account.balance = 100;
  10. 复制代码

Good:

  1. function makeBankAccount() {
  2. // 私有变量
  3. let balance = 0;
  4. function getBalance() {
  5. return balance;
  6. }
  7. function setBalance(amount) {
  8. // ... 在更新 balance 前,对 amount 进行校验
  9. balance = amount;
  10. }
  11. return {
  12. // ...
  13. getBalance,
  14. setBalance,
  15. };
  16. }
  17. const account = makeBankAccount();
  18. account.setBalance(100);
  19. 复制代码

使用私有变量

可以用闭包来创建私有变量
Bad:

  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
  11. 复制代码

Good:

  1. function makeEmployee(name) {
  2. return {
  3. getName() {
  4. return name;
  5. },
  6. };
  7. }
  8. const employee = makeEmployee('John Doe');
  9. console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
  10. delete employee.name;
  11. console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
  12. 复制代码

类

使用 class

在 ES2015/ES6 之前,没有类的语法,只能用构造函数的方式模拟类,可读性非常差。
Bad:

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

Good:

  1. // 动物
  2. class Animal {
  3. constructor(age) {
  4. this.age = age
  5. };
  6. move() {};
  7. }
  8. // 哺乳动物
  9. class Mammal extends Animal{
  10. constructor(age, furColor) {
  11. super(age);
  12. this.furColor = furColor;
  13. };
  14. liveBirth() {};
  15. }
  16. // 人类
  17. class Human extends Mammal{
  18. constructor(age, furColor, languageSpoken) {
  19. super(age, furColor);
  20. this.languageSpoken = languageSpoken;
  21. };
  22. speak() {};
  23. }
  24. 复制代码

链式调用

这种模式相当有用,可以在很多库中发现它的身影,比如 jQuery、Lodash 等。它让你的代码简洁优雅。实现起来也非常简单,在类的方法最后返回 this 可以了。
Bad:

  1. class Car {
  2. constructor(make, model, color) {
  3. this.make = make;
  4. this.model = model;
  5. this.color = color;
  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('Ford','F-150','red');
  21. car.setColor('pink');
  22. car.save();
  23. 复制代码

Good:

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

不要滥用继承

很多时候继承被滥用,导致可读性很差,要搞清楚两个类之间的关系,继承表达的一个属于关系,而不是包含关系,比如 Human->Animal vs. User->UserDetails
Bad:

  1. class Employee {
  2. constructor(name, email) {
  3. this.name = name;
  4. this.email = email;
  5. }
  6. // ...
  7. }
  8. // TaxData(税收信息)并不是属于 Employee(雇员),而是包含关系。
  9. class EmployeeTaxData extends Employee {
  10. constructor(ssn, salary) {
  11. super();
  12. this.ssn = ssn;
  13. this.salary = salary;
  14. }
  15. // ...
  16. }
  17. 复制代码

Good:

  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. }
  18. 复制代码

SOLID

SOLID 是几个单词首字母组合而来,分别表示 单一功能原则、开闭原则、里氏替换原则、接口隔离原则以及依赖反转原则。

单一功能原则

如果一个类干的事情太多太杂,会导致后期很难维护。我们应该厘清职责,各司其职减少相互之间依赖。
Bad:

  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. }
  14. 复制代码

Good:

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

开闭原则

“开”指的就是类、模块、函数都应该具有可扩展性,“闭”指的是它们不应该被修改。也就是说你可以新增功能但不能去修改源码。
Bad:

  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. // 传递 response 并 return
  21. });
  22. } else if (this.adapter.name === 'httpNodeAdapter') {
  23. return makeHttpCall(url).then((response) => {
  24. // 传递 response 并 return
  25. });
  26. }
  27. }
  28. }
  29. function makeAjaxCall(url) {
  30. // 处理 request 并 return promise
  31. }
  32. function makeHttpCall(url) {
  33. // 处理 request 并 return promise
  34. }
  35. 复制代码

Good:

  1. class AjaxAdapter extends Adapter {
  2. constructor() {
  3. super();
  4. this.name = 'ajaxAdapter';
  5. }
  6. request(url) {
  7. // 处理 request 并 return promise
  8. }
  9. }
  10. class NodeAdapter extends Adapter {
  11. constructor() {
  12. super();
  13. this.name = 'nodeAdapter';
  14. }
  15. request(url) {
  16. // 处理 request 并 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. // 传递 response 并 return
  26. });
  27. }
  28. }
  29. 复制代码

里氏替换原则

名字很唬人,其实道理很简单,就是子类不要去重写父类的方法。
Bad:

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

Good:

  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);
  36. 复制代码

接口隔离原则

JavaScript 几乎没有接口的概念,所以这条原则很少被使用。官方定义是“客户端不应该依赖它不需要的接口”,也就是接口最小化,把接口解耦。
Bad:

  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. });
  19. 复制代码

Good:

  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. });
  26. 复制代码

依赖反转原则

说就两点:

  1. 高层次模块不能依赖低层次模块,它们依赖于抽象接口。
  2. 抽象接口不能依赖具体实现,具体实现依赖抽象接口。

总结下来就两个字,解耦。
Bad:

  1. // 库存查询
  2. class InventoryRequester {
  3. constructor() {
  4. this.REQ_METHODS = ['HTTP'];
  5. }
  6. requestItem(item) {
  7. // ...
  8. }
  9. }
  10. // 库存跟踪
  11. class InventoryTracker {
  12. constructor(items) {
  13. this.items = items;
  14. // 这里依赖一个特殊的请求类,其实我们只是需要一个请求方法。
  15. this.requester = new InventoryRequester();
  16. }
  17. requestItems() {
  18. this.items.forEach((item) => {
  19. this.requester.requestItem(item);
  20. });
  21. }
  22. }
  23. const inventoryTracker = new InventoryTracker(['apples', 'bananas']);
  24. inventoryTracker.requestItems();
  25. 复制代码

Good:

  1. // 库存跟踪
  2. class InventoryTracker {
  3. constructor(items, requester) {
  4. this.items = items;
  5. this.requester = requester;
  6. }
  7. requestItems() {
  8. this.items.forEach((item) => {
  9. this.requester.requestItem(item);
  10. });
  11. }
  12. }
  13. // HTTP 请求
  14. class InventoryRequesterHTTP {
  15. constructor() {
  16. this.REQ_METHODS = ['HTTP'];
  17. }
  18. requestItem(item) {
  19. // ...
  20. }
  21. }
  22. // webSocket 请求
  23. class InventoryRequesterWS {
  24. constructor() {
  25. this.REQ_METHODS = ['WS'];
  26. }
  27. requestItem(item) {
  28. // ...
  29. }
  30. }
  31. // 通过依赖注入的方式将请求模块解耦,这样我们就可以很轻易的替换成 webSocket 请求。
  32. const inventoryTracker = new InventoryTracker(['apples', 'bananas'], new InventoryRequesterHTTP());
  33. inventoryTracker.requestItems();
  34. 复制代码

测试

随着项目变得越来越庞大,时间线拉长,有的老代码可能半年都没碰过,如果此时上线,你有信心这部分代码能正常工作吗?测试的覆盖率和你的信心是成正比的。
PS: 如果你发现你的代码很难被测试,那么你应该优化你的代码了。

单一化

Bad:

  1. import assert from 'assert';
  2. describe('MakeMomentJSGreatAgain', () => {
  3. it('handles date boundaries', () => {
  4. let date;
  5. date = new MakeMomentJSGreatAgain('1/1/2015');
  6. date.addDays(30);
  7. assert.equal('1/31/2015', date);
  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. });
  16. 复制代码

Good:

  1. import assert from 'assert';
  2. describe('MakeMomentJSGreatAgain', () => {
  3. it('handles 30-day months', () => {
  4. const date = new MakeMomentJSGreatAgain('1/1/2015');
  5. date.addDays(30);
  6. assert.equal('1/31/2015', date);
  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. });
  19. 复制代码

异步

不再使用回调

不会有人愿意去看嵌套回调的代码,用 Promises 替代回调吧。
Bad:

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

Good:

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

Async/Await 比起 Promises 更简洁

Bad:

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

Good:

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

错误处理

不要忽略抛异常

Bad:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. console.log(error);
  5. }
  6. 复制代码

Good:

  1. try {
  2. functionThatMightThrow();
  3. } catch (error) {
  4. // 这一种选择,比起 console.log 更直观
  5. console.error(error);
  6. // 也可以在界面上提醒用户
  7. notifyUserOfError(error);
  8. // 也可以把异常传回服务器
  9. reportErrorToService(error);
  10. // 其他的自定义方法
  11. }
  12. 复制代码

不要忘了在 Promises 抛异常

Bad:

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

Good:

  1. getdata()
  2. .then((data) => {
  3. functionThatMightThrow(data);
  4. })
  5. .catch((error) => {
  6. // 这一种选择,比起 console.log 更直观
  7. console.error(error);
  8. // 也可以在界面上提醒用户
  9. notifyUserOfError(error);
  10. // 也可以把异常传回服务器
  11. reportErrorToService(error);
  12. // 其他的自定义方法
  13. });
  14. 复制代码

代码风格

代码风格是主观的,争论哪种好哪种不好是在浪费生命。市面上有很多自动处理代码风格的工具,选一个喜欢就行了,我们来讨论几个非自动处理的部分。

常量大写

Bad:

  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 {}
  9. 复制代码

Good:

  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 {}
  9. 复制代码

先声明后调用

就像我们看报纸文章一样,从上到下看,所以为了方便阅读把函数声明写在函数调用前面。
Bad:

  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(employee);
  28. review.perfReview();
  29. 复制代码

Good:

  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();
  29. 复制代码

注释

只有业务逻辑需要注释

代码注释不是越多越好。
Bad:

  1. function hashIt(data) {
  2. // 这是初始值
  3. let hash = 0;
  4. // 数组的长度
  5. const length = data.length;
  6. // 循环数组
  7. for (let i = 0; i < length; i++) {
  8. // 获取字符代码
  9. const char = data.charCodeAt(i);
  10. // 修改 hash
  11. hash = ((hash << 5) - hash) + char;
  12. // 转换为32位整数
  13. hash &= hash;
  14. }
  15. }
  16. 复制代码

Good:

  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. // 转换为32位整数
  8. hash &= hash;
  9. }
  10. }
  11. 复制代码

删掉注释的代码

git 存在的意义就是保存你的旧代码,所以注释的代码赶紧删掉吧。
Bad:

  1. doStuff();
  2. // doOtherStuff();
  3. // doSomeMoreStuff();
  4. // doSoMuchStuff();
  5. 复制代码

Good:

  1. doStuff();
  2. 复制代码

不要记日记

记住你有 git!,git log 可以帮你干这事。
Bad:

  1. /**
  2. * 2016-12-20: 删除了 xxx
  3. * 2016-10-01: 改进了 xxx
  4. * 2016-02-03: 删除了第12行的类型检查
  5. * 2015-03-14: 增加了一个合并的方法
  6. */
  7. function combine(a, b) {
  8. return a + b;
  9. }
  10. 复制代码

Good:

  1. function combine(a, b) {
  2. return a + b;
  3. }
  4. 复制代码

注释不需要高亮

注释高亮,并不能起到提示的作用,反而会干扰你阅读代码。
Bad:

  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. };
  14. 复制代码

Good:

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