编写更简洁的JavaScript

clean-code-javascript的中文翻译

变量


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

Bad:

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

Good:

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

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

Bad:

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

Good:

  1. getUser();

使用可搜索的名称

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

Bad:

  1. // 86400000 是什么东西?
  2. setTimeout(blastOff, 86400000);

Good:

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

使用解释性的变量

Bad:

  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]);

Good:

  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);

避免心理映射

显示比隐式更好

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. });

Good:

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

不添加不必要的上下文

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

Bad:

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

Good:

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

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

Bad:

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

Good:

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

函数


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

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

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

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

Bad:

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

Good:

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

函数应当只做一件事情

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

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. }

Good:

  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. }

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

Bad:

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

Good:

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

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

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

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. }

Good:

  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. }

移除冗余代码

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

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

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

让这个抽象正确是关键的, 这是为什么要你遵循 Classes 那一章的 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. }

Good:

  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. }

使用 Object.assign 设置默认对象

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);

Good:

  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);

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

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

Bad:

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

Good:

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

避免副作用 (第一部分)

如果函数进行不是接收参数然后返回值这种操作,就会产生副作用。副作用可能是修改了某些全局变量或者是写入到一个文件中。

Bad:

  1. let name = "xiao ming";
  2. function splitName() {
  3. name = name.split(" ");
  4. }
  5. splitName();
  6. console.log(name)
  7. // ["xiao", "ming"]

Good:

  1. function splitName(name) {
  2. return name.split(" ")
  3. };
  4. const name = "xiao ming";
  5. const newName = splitName(name);
  6. console.log(name); // xiao ming
  7. console.log(newName) ["xiao", "ming"]

避免副作用(第二部分)

在JavaScript中,一些值是不会变的(immutable)而一些则是可以变动的(mutable)。对象(object)和数组(arrays)就是两种可变的值,因此在作为函数参数进行传递时要非常小心。函数可以更改对象的值或者是修改一个数组中的内容,这些很容易造成bug。

假设有一个函数接收一个数组参数(可以把这个数组想象成一个购物车)。如果函数中对这个数组进行更改——添加多一个商品。其它有用到该数组的函数也会受影响。这不是挺不错的嘛,怎么会不好呢?让我们想象一个坏情形:

用户点击购买按钮后调用purchase函数发送网络请求,把购物车中的数据传递给服务端。由于网络连接不好,purchase函数一直重试请求。如果这个时候用户不小心将某件他们不想要的商品添加至购物车会怎么办?如果真的出现这种情形而且网络请求发送成功了,那么purchase函数就会将不小心添加商品后的数据发送至服务端。

一个好的解决办法就是在调用addItemToCart函数前克隆一份购物车数据,对克隆的数据进行操作后再返回。这样可以保证其他使用购物车数据的函数不会受到影响。

对于这个方法有两个注意事项:

  • 也可能存在你真的想要改变传入的对象这种情形。当你接受了这个语法训练以后你会发现那些情形非常少见。大多数都是可以改写成无副作用的形式。
  • 克隆大对象在性能方面可能非常昂贵。幸运的是,这在实践中并不是一个大问题,因为有一些很棒的库允许这种编程方法速度更快,并且不像手动克隆对象和数组那样占用内存。

Bad:

  1. const addItemToCart = (cart, item) => {
  2. cart.push({item, date: Date.now()})
  3. }

Good:

  1. const addItemToCart = (cart, item) => {
  2. return [...cart, {item, date: Date.now()}]
  3. }

不写全局函数

污染全局在JavaScript中是一个坏操作,因为这可能跟你引入的其他库发生冲突,导致你的API的调用者无法判断最终在生产环境中出现异常。我们想想一个例子:如果你想要在JavaScript的原生Array方法中写入一个diff方法,用于展示两个数组间的区别,要怎么做呢?你可以在Array.prorotype中添加一个新方法,但是也可能跟其它有相同想法的库发生冲突。假如其它的库只是用diff去对数组的第一个和最后一个元素进行判断呢?这就是为什么使用ES2015/ES6中的classes 会更好而且更容易全局扩展Array

Bad:

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

Good:

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

支持函数式编程而非命令式编程

JavaScript不像Haskell那样是一种函数式语言,但是它有一种函数式的风格。函数式语言更加简洁且容易测试。尽量使用函数式编程风格。

Bad:

  1. const programmerOutput = [
  2. {
  3. name: 'xiao ming',
  4. linesOfCode: 100
  5. },
  6. {
  7. name: 'xiao hong',
  8. linesOfCode: 200
  9. },
  10. {
  11. name: 'xiao pang',
  12. linesOfCode: 300
  13. }
  14. ];
  15. let totalOutput = 0;
  16. for(let i = 0; i < programmerOutput.length; i++) {
  17. totalOutput += programmerOutput[i].linesOfCode;
  18. }

Good:

  1. const programmerOutput = [
  2. {
  3. name: 'xiao ming',
  4. linesOfCode: 100
  5. },
  6. {
  7. name: 'xiao hong',
  8. linesOfCode: 200
  9. },
  10. {
  11. name: 'xiao pang',
  12. linesOfCode: 300
  13. }
  14. ];
  15. const totalOutput = programmerOutput.reduce(
  16. (totalLines, output) => totalLines + output.linesOfCode, 0
  17. )

封装条件

Bad:

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

Good:

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

避免使用否定条件

Bad:

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

Good:

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

避免条件句

这看起来像一个根本不可能的任务。当第一次听到这个的时候,大多数人都会说,”没有 if 判断我什么也做不了啊”。答案就是你可以用多态在不同的例子中实现相同的任务。第二个问题通常会是, “那挺好的但是我为什么要那样做”。答案是我们之前学到的一个干净的代码概念:一个函数应该只做一件事。如果你有很多类(classes)和函数(functions)中都存在 if 判断,你告诉你的用户你的函数做了不止一件事。记住,只要做一件事。

Bad:

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

Good:

  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. }

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

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. }

Good:

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

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

如果你使用的是字符串和整数之类的原始值类型,虽然不能使用多态性,但仍然需要进行类型检查,那么应该考虑使用TypeScript。它是普通JavaScript的优秀替代品,因为它在标准JavaScript语法的基础上为您提供了静态类型。手动检查普通JavaScript的问题在于,要想把它做好,需要太多额外的赘言,以至于你得到的“类型安全”并不能弥补失去的可读性。保持JavaScript干净,编写良好的测试,并进行良好的代码评审。除了使用TypeScript之外,不然所有这些工作都要做。(就像我说的,这是一个很好的选择!)

Bad:

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

Good:

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

不要过度优化

现代浏览器在运行时进行了大量的优化。很多时候,如果你在优化,那就是在浪费时间。这个资源可以看到哪里缺少优化。主要针对那些进行优化除非它们已经被解决了。

Bad:

  1. // 在旧浏览器上,每次迭代都使用未缓存的`列表长度`会很昂贵
  2. // 因为`列表长度`重新计算。在现代浏览器中,这是经过优化的。
  3. for (let i = 0, len = list.length; i < len; i++) {
  4. // ...
  5. }

Good:

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

删除死代码

死代码和重复代码一样糟糕。没有理由把它放在你的代码库里。如果没有被调用,就把它删了!如果你仍然需要它,它在你的版本历史记录中仍然是安全的。

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");

Good:

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

对象和数据结构


使用getters和setters

使用getters和setters来操作对象上的数据可能会比简单的在对象上查看值更好。”为什么呢?”你可能会问。以下是一些原因:

  • 当你想要在获取对象值的时候做更多的操作,你不需要在你的代码库中查找然后改变所有的引用。
  • 在赋值(set)操作时可以添加校验。
  • 封装内部表达式。
  • 在获取值和设置值的时候可以更简单的输出日志跟异常处理。
  • 你可以懒加载你对象的值,就好比说从服务器中获取的。

Bad:

  1. function makeBankAccount() {
  2. //..
  3. return {
  4. balance: 0
  5. }
  6. }
  7. const account = makeBankAccount();
  8. account.balance = 100;

Good:

  1. function makeBankAccount() {
  2. // 这个是私有的
  3. let balance = 0;
  4. // 一个getter,让外部访问返回下边的对象
  5. function getBalance() {
  6. return balance;
  7. }
  8. // 一个setter,让外部访问返回下边的对象
  9. // a "setter", made public via the returned object below
  10. function setBalance(amount) {
  11. // ... 可以在赋值前添加校验
  12. balance = amount;
  13. }
  14. return {
  15. // ...
  16. getBalance,
  17. setBalance
  18. };
  19. }
  20. const account = makeBankAccount();
  21. account.setBalance(100);

让对象包含私有成员

这个可以通过闭包实现(ES5及以下)

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("xiao ming");
  8. console.log(`Employee name: ${employee.getName()}`) // Employee name: xiao ming
  9. delete employee.name;
  10. console.log(`Employee name: ${employee.getName()}`) // Employee name:undefined

Good:

  1. function makeEmployee(name) {
  2. return {
  3. getName() {
  4. return name;
  5. }
  6. }
  7. }
  8. const employee = makeEmployee("xiao ming");
  9. console.log(`Employee name: ${employee.getName()}`); // Employee name: xiao ming
  10. delete employee.name;
  11. console.log(`Employee name: ${employee.getName()}`); // Employee name: xiao ming


优先考虑 ES2015 / ES6 的 classes 而不是ES5的普通函数

对于传统的ES5类来说,很难获得可读的类继承、构造和方法定义。

Bad:

  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. }
  23. Human.prototype = Object.create(Mammal.prototype);
  24. Human.prototype.constructor = Human;
  25. Human.prototype.speak = function speak() {};

Good:

  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. }

使用方法链

这种模式在JavaScript中是非常有帮助的而且你可以在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();

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. // 返回this
  10. return this;
  11. }
  12. setModel(model) {
  13. this.model = model;
  14. // 返回this
  15. return this;
  16. }
  17. setColor(color) {
  18. this.color = color;
  19. // 返回this
  20. return this;
  21. }
  22. save() {
  23. console.log(this.make, this.model, this.color);
  24. // 返回this
  25. return this;
  26. }
  27. }
  28. const car = new Car("Ford", "F-150", "red").setColor("pink").save();

倾向合成而非继承

正如 Gang of Four在 Design Patterns(设计模式)中所说的那样,在可能的情况下,您应该更喜欢组合而不是继承。使用继承和组合有很多很好的理由。这条格言的要点是,如果你的思维本能地倾向于继承,那么试着思考组合是否能更好地模拟你的问题。在某些情况下,它是可以的。

你可能会想,“我什么时候应该使用继承?”这取决于你手头的问题,但这是一个很好的列表,列出了什么时候继承比组合更有意义:

  1. 你的继承代表一种“是一种”关系,而不是一种“有一种”关系。(人类 -> 动物, 用户 -> 用户详情)
  2. 你可以重用来自基类的代码(人类可以像所有动物一样移动)。
  3. 你希望通过更改基类来对派生类进行全局更改。(改变所有动物移动时的热量消耗)。

Bad:

  1. class Employee {
  2. constructor(name, email) {
  3. this.name = name;
  4. this.email = email;
  5. }
  6. }
  7. // 这种方法不好是因为 Employee 存在税务数据, EmployeeTaxData不是Employee的一种类型
  8. class EmployeeTaxData extends Employee {
  9. constructor(ssn, salary) {
  10. super();
  11. this.ssn = ssn;
  12. this.salary = salary;
  13. }
  14. // ...
  15. }

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. }

solid


单一责任原则(Single Responsibility Principle (SRP))

正如在 Clean Code 中所述,“一个类改变的原因不应该超过一个”。在一个类中塞满很多函数是很有诱惑力的,就好像你在飞机上只能带一个手提箱。这样做的问题是,你的类在概念上没有连贯性,它会给它很多改变的理由。尽量减少更改类的次数是很重要的。这一点很重要,因为如果一个类中有太多的功能,而您修改了其中的一部分,则很难理解这将如何影响代码库中的其他依赖模块。

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. }

Good:

  1. class UserAuth {
  2. construtor(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. }

开闭原则

正如 Bertrand Meyer所说,“软件实体(类、模块、函数等)应该为扩展而打开,但为修改而关闭。”这意味着什么呢?这个原则基本上是说,你应该允许用户添加新的功能,而不必更改原有的代码。

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. // ...
  21. })
  22. } else if (this.adapter.name === "nodeAdapter") {
  23. return makeHttpCall(url).then(response => {
  24. // ...
  25. })
  26. }
  27. }
  28. }
  29. function makeAjaxCall(url) {
  30. // 请求并返回promise
  31. }
  32. function makeHttpCall(url) {
  33. // 请求并返回promise
  34. }

Good:

  1. class AjaxAdapter extends Adapter {
  2. constructor() {
  3. super();
  4. this.name = "ajaxAdapter";
  5. }
  6. request(url) {
  7. // 请求并返回promise
  8. }
  9. }
  10. class NodeAdapter extends Adapter {
  11. constructor() {
  12. super();
  13. this.name = "nodeAdapter";
  14. }
  15. request(url) {
  16. // 请求并返回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. // ...
  26. })
  27. }
  28. }

里氏替换原则

对于一个非常简单的概念来说,这是一个可怕的术语。它被正式定义为“如果S是T的子类型,那么T类型的对象可以被S类型的对象替换(即S类型的对象可以替换T类型的对象),而不改变该程序的任何期望属性(正确性、执行的任务等)。”这是一个更可怕的定义。

最好的解释是,如果有父类和子类,那么基类和子类可以互换使用,而不会得到错误的结果。这可能仍然令人困惑,所以让我们看一看经典的正方形-矩形示例。从数学上讲,正方形是矩形,但如果通过继承使用“is-a”关系对其进行建模,你很快就会遇到麻烦。

Bad:

  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();
  37. // Square返回25, 但实际应该是20
  38. rectangle.render(area);
  39. })
  40. }
  41. const rectangles = [new Rectangle(), new Rectangle(), new Square()];
  42. renderLargeRectangles(rectangles);

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);

接口隔离原则

JavaScript没有接口,所以这个原则没有其他原则那么严格。然而,即使JavaScript缺少类型系统,它也很重要。

接口隔离原则声明“不应该强迫客户依赖于他们不使用的接口。” 由于是鸭子类型,接口在JavaScript中是隐式契约。

在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.settings.animationModule.setup();
  9. }
  10. traverse() {
  11. // ...
  12. }
  13. }
  14. const $ = new DOMTraverser({
  15. rootNode: document.getElementsByTagName("body"),
  16. animationModule(){} // 在大多数情况下我们在遍历时都不需要动画
  17. })

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. })

依赖反转原理

这一原则规定了两个基本事项:

  1. 高级模块不应依赖于低级模块。两者都应该依赖于抽象。

  2. 抽象不应该依赖于细节。细节应该取决于抽象。

这一点一开始可能很难理解,但是如果你使用过AngularJS,你就可能已经看到了依赖注入(DI)形式的这一原则的实现。虽然它们不是完全相同的概念,但是依赖倒置原理阻止高级模块了解其低级模块的细节并设置它们。它可以通过DI来实现这一点。这样做的一个巨大好处是减少了模块之间的耦合。耦合是一种非常糟糕的开发模式,因为它使代码很难重构。

如前所述,JavaScript没有接口,因此依赖的抽象是隐式契约。也就是说,一个对象/类向另一个对象/类公开的方法和属性。在下面的示例中,隐式约定是InventoryTracker的任何请求模块都将具有requestItems方法。

Bad:

  1. class InventoryRequester {
  2. constructor() {
  3. this.REQ_METHODS = ["HTTP"];
  4. }
  5. requstItem(item) {
  6. // ...
  7. }
  8. }
  9. class InventoryTracker {
  10. constructor(items) {
  11. this.items = items;
  12. // 我们已经创建了对特定请求实现的依赖关系。
  13. // 我们应该让requestItems依赖于一个请求方法:`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();

Good:

  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. // 通过在外部构造依赖项并注入它们,我们可以很容易地
  29. // 将我们的请求模块替换为使用WebSockets的新模块。
  30. const inventoryTracker = new InventoryTracker (
  31. ["apples", "bananas"],
  32. new InventoryRequesterV2()
  33. )
  34. inventoryTracker.requestItems();

测试


测试比运输更重要。如果您没有测试或者测试量不足,那么每次发布代码时,你都不能确定自己没有破坏任何东西。决定什么是足够的数量取决于您的团队,但是拥有100%的覆盖率(所有语句和分支)是您获得非常高的信心和开发人员的安心的方式。这意味着除了拥有一个优秀的测试框架外,还需要使用一个好的覆盖工具

没有理由不写测试。有很多好的JS测试框架,所以找一个你的团队更喜欢的。当你找到一个对你的团队有效的方法时,就要始终为你引入的每一个新特性/模块编写测试。如果您首选的方法是测试驱动开发(Test-Driven Development,TDD),那就很好了,但主要的一点是在启动任何特性或重构现有特性之前,确保你达到了覆盖率目标。

一个测试一个概念

Bad:

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

Good:

  1. import assert from "assert";
  2. describe("MomentJS", () => {
  3. it("handles 30-day months", () => {
  4. const date = new MomentJS("1/1/2015");
  5. date.addDays(30);
  6. assert.equal("1/31/2015", date);
  7. });
  8. it("handles leap year", () => {
  9. const date = new MomentJS("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 MomentJS("2/1/2015");
  15. date.addDays(28);
  16. assert.equal("03/01/2015", date);
  17. });
  18. });

并发


使用 Promises 而不是回调函数

回调看起来不简洁,它们会导致过多的嵌套。对于ES2015/ES6,Promises是一种内置的全局类型。使用它们!

Bad:

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

Good:

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

Async / Await 比Promises更简洁

Promises是回调函数的一个非常简洁的替代方法,但是ES2017/ES8带来了async和await,这提供了一个更干净的解决方案。你所需要的只是一个以async关键字为前缀的函数,然后就可以在不使用then函数链的情况下强制编写逻辑了。如果你现在可以利用ES2017/ES8的功能,请使用此功能!

Bad:

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

Good:

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

错误处理


抛出错误是一件好事情!它们意味着运行时已经成功地识别了程序中的某些错误,它通过停止当前堆栈上的函数执行、终止进程(在Node中)并在控制台中用堆栈跟踪来通知你。

不要忽视异常捕获

对捕获到的错误不采取任何措施都不会使你有能力修复或对所述错误作出反应。将错误记录到控制台(console.log)不是很好,因此它容易迷失在控制台输出的一大堆信息中。如果你使用try/catch包装任何代码,这意味着你认为可能会在那里发生错误,因此你应该为此制定计划或创建代码路径。

Bad:

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

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. }

不要忽视 rejected 状态的 promises

跟你不应该忽略try/catch中捕获的错误一样的原因。

Bad:

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

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. });

格式化


格式化是主观的。像这里的许多规则一样,没有硬性规定你必须遵守。要点是不要争论格式问题。有很多工具可以实现自动化。用一个就行了!工程师就格式问题争论是浪费时间和金钱。

统一使用大写字母

JavaScript是非类型化的,所以大写告诉你很多关于变量、函数等的信息。这些规则是主观的,所以你的团队可以选择他们想要的任何东西。关键是,无论你们选择什么,都要始终如一。

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 {}

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 {}

函数调用者和被调用者应该是接近的

如果一个函数调用另一个函数,在源文件中垂直关闭这些函数。理想情况下,让调用者在被调用者的正上方。我们倾向于自上而下地阅读代码,就像读报纸一样。因此,让你的代码以这种方式阅读。

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();

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();

注释


仅对具有业务逻辑复杂性的内容进行注释。

评论是道歉,不是要求。好的代码主要是文档本身。

Bad:

  1. function hashIt(data) {
  2. // hash
  3. let hash = 0;
  4. // string 的长度
  5. const length = data.length;
  6. // 遍历data中的元素
  7. for (let i = 0; i < length; i++) {
  8. // 获取元素的charCode
  9. const char = data.charCodeAt(i);
  10. // 获取hash
  11. hash = (hash << 5) - hash + char;
  12. // 转成32位整数
  13. hash &= hash;
  14. }
  15. }

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. }

不要在代码库中留下注释掉的代码

版本控制的存在是有一定道理的,就让旧代码存在在你的历史中。

Bad:

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

Good:

  1. doStuff();

不要有日志注释

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

Bad:

  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. }

Good:

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

避免位置标记

它们通常只会让人厌恶。让函数和变量名以及适当的缩进和格式为代码提供可视化结构。

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. };

Good:

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