如何写出优雅的 JS 代码,变量和函数的正确写法

开发 前端
在开发中,变量名,函数名一般要做到清晰明了,尽量做到看名字就能让人知道你的意图,所以变量和函数命名是挺重要,今天来看看如果较优雅的方式给变量和函数命名。

在开发中,变量名,函数名一般要做到清晰明了,尽量做到看名字就能让人知道你的意图,所以变量和函数命名是挺重要,今天来看看如果较优雅的方式给变量和函数命名。

[[325239]]

一、变量

使用有意义和可发音的变量名

  1. // 不好的写法 
  2. const yyyymmdstr = moment().format("YYYY/MM/DD"); 
  3.  
  4. // 好的写法 
  5. const currentDate = moment().format("YYYY/MM/DD"); 

对同一类型的变量使用相同的词汇

  1. // 不好的写法 
  2. getUserInfo(); 
  3. getClientData(); 
  4. getCustomerRecord(); 
  5.  
  6. // 好的写法 
  7. getUser(); 

使用可搜索的名字

我们读的会比我们写的多得多,所以如果命名太过随意不仅会给后续的维护带来困难,也会伤害了读我们代码的开发者。让你的变量名可被读取,像 buddy.js 和 ESLint 这样的工具可以帮助识别未命名的常量。

  1. // 不好的写法 
  2. // 86400000 的用途是什么? 
  3. setTimeout(blastOff, 86400000); 
  4.  
  5. // 好的写法 
  6. const MILLISECONDS_IN_A_DAY = 86_400_000
  7. setTimeout(blastOff, MILLISECONDS_IN_A_DAY); 

使用解释性变量

  1. // 不好的写法 
  2. const address = "One Infinite Loop, Cupertino 95014"
  3. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
  4. saveCityZipCode( 
  5.   address.match(cityZipCodeRegex)[1], 
  6.   address.match(cityZipCodeRegex)[2] 
  7. ); 
  8.  
  9.  
  10. // 好的写法 
  11. const address = "One Infinite Loop, Cupertino 95014"
  12. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
  13. const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; 
  14. saveCityZipCode(city, zipCode); 

避免费脑的猜测

显式用于隐式

  1. // 不好的写法 
  2. const locations = ["Austin", "New York", "San Francisco"]; 
  3. locations.forEach(l => { 
  4.   doStuff(); 
  5.   doSomeOtherStuff(); 
  6.   // ... 
  7.   // ... 
  8.   // ... 
  9.   // 等等,“l”又是什么? 
  10.   dispatch(l); 
  11.  
  12. // 好的写法 
  13. const locations = ["Austin", "New York", "San Francisco"]; 
  14. locations.forEach(location => { 
  15.   doStuff(); 
  16.   doSomeOtherStuff(); 
  17.   // ... 
  18.   // ... 
  19.   // ... 
  20.   dispatch(location); 
  21. }); 

无需添加不必要的上下文

如果类名/对象名已经说明了,就无需在变量名中重复。

  1. // 不好的写法 
  2. const Car = { 
  3.   carMake: "Honda", 
  4.   carModel: "Accord", 
  5.   carColor: "Blue" 
  6. }; 
  7.  
  8. function paintCar(car) { 
  9.   car.carColor = "Red"
  10. // 好的写法 
  11. const Car = { 
  12.   make: "Honda", 
  13.   model: "Accord", 
  14.   color: "Blue" 
  15. }; 
  16.  
  17. function paintCar(car) { 
  18.   car.color = "Red"

使用默认参数代替逻辑或(与)运算

  1. // 不好的写法 
  2. function createMicrobrewery(name) { 
  3.   const breweryName = name || "Hipster Brew Co."; 
  4.   // ... 
  5. // 好的写法 
  6. function createMicrobrewery(name = "Hipster Brew Co.") { 
  7.   // ... 

二、函数

函数参数(理想情况下为2个或更少)

限制函数参数的数量是非常重要的,因为它使测试函数变得更容易。如果有三个以上的参数,就会导致组合爆炸,必须用每个单独的参数测试大量不同的情况。

一个或两个参数是理想的情况,如果可能,应避免三个参数。除此之外,还应该合并。大多数情况下,大于三个参数可以用对象来代替。

  1. // 不好的写法 
  2. function createMenu(title, body, buttonText, cancellable) { 
  3.   // ... 
  4.  
  5. createMenu("Foo", "Bar", "Baz", true); 
  6.  
  7. // 好的写法 
  8. function createMenu({ title, body, buttonText, cancellable }) { 
  9.   // ... 
  10.  
  11. createMenu({ 
  12.   title: "Foo", 
  13.   body: "Bar", 
  14.   buttonText: "Baz", 
  15.   cancellable: true 
  16. }); 

函数应该只做一件事

这是目前为止软件工程中最重要的规则。当函数做不止一件事时,它们就更难组合、测试和推理。可以将一个函数隔离为一个操作时,就可以很容易地重构它,代码也会读起来更清晰。

  1. // 不好的写法 
  2. function emailClients(clients) { 
  3.   clients.forEach(client => { 
  4.     const clientRecord = database.lookup(client); 
  5.     if (clientRecord.isActive()) { 
  6.       email(client); 
  7.     } 
  8.   }); 
  9.  
  10. // 好的写法 
  11.  
  12. function emailActiveClients(clients) { 
  13.   clients.filter(isActiveClient).forEach(email); 
  14.  
  15. function isActiveClient(client) { 
  16.   const clientRecord = database.lookup(client); 
  17.   return clientRecord.isActive(); 

函数名称应说明其作用

  1. // 不好的写法 
  2. function addToDate(date, month) { 
  3.   // ... 
  4.  
  5. const date = new Date(); 
  6.  
  7. // 从函数名称很难知道添加什么 
  8. addToDate(date, 1); 
  9.  
  10. // 好的写法 
  11. function addMonthToDate(month, date) { 
  12.   // ... 
  13.  
  14. const date = new Date(); 
  15. addMonthToDate(1, date); 

函数应该只有一个抽象层次

当有一个以上的抽象层次函数,意味该函数做得太多了,需要将函数拆分可以实现可重用性和更简单的测试。

  1. // 不好的写法 
  2. function parseBetterJSAlternative(code) { 
  3.   const REGEXES = [ 
  4.     // ... 
  5.   ]; 
  6.  
  7.   const statements = code.split(" "); 
  8.   const tokens = []; 
  9.   REGEXES.forEach(REGEX => { 
  10.     statements.forEach(statement => { 
  11.       // ... 
  12.     }); 
  13.   }); 
  14.  
  15.   const ast = []; 
  16.   tokens.forEach(token => { 
  17.     // lex... 
  18.   }); 
  19.  
  20.   ast.forEach(node => { 
  21.     // parse... 
  22.   }); 
  23.  
  24. // 好的写法 
  25. function parseBetterJSAlternative(code) { 
  26.   const tokens = tokenize(code); 
  27.   const syntaxTree = parse(tokens); 
  28.   syntaxTree.forEach(node => { 
  29.     // parse... 
  30.   }); 
  31.  
  32. function tokenize(code) { 
  33.   const REGEXES = [ 
  34.     // ... 
  35.   ]; 
  36.  
  37.   const statements = code.split(" "); 
  38.   const tokens = []; 
  39.   REGEXES.forEach(REGEX => { 
  40.     statements.forEach(statement => { 
  41.       tokens.push(/* ... */); 
  42.     }); 
  43.   }); 
  44.  
  45.   return tokens; 
  46.  
  47. function parse(tokens) { 
  48.   const syntaxTree = []; 
  49.   tokens.forEach(token => { 
  50.     syntaxTree.push(/* ... */); 
  51.   }); 
  52.  
  53.   return syntaxTree; 

删除重复的代码

尽量避免重复的代码,重复的代码是不好的,它意味着如果我们需要更改某些逻辑,要改很多地方。

通常,有重复的代码,是因为有两个或多个稍有不同的事物,它们有很多共同点,但是它们之间的差异迫使我们编写两个或多个独立的函数来完成许多相同的事情。 删除重复的代码意味着创建一个仅用一个函数/模块/类就可以处理这组不同事物的抽象。

获得正确的抽象是至关重要的,这就是为什么我们应该遵循类部分中列出的 「SOLID原则」。糟糕的抽象可能比重复的代码更糟糕,所以要小心!说了这么多,如果你能做一个好的抽象,那就去做吧!不要重复你自己,否则你会发现自己在任何时候想要改变一件事的时候都要更新多个地方。

「设计模式的六大原则有」

  • Single Responsibility Principle:单一职责原则
  • Open Closed Principle:开闭原则
  • Liskov Substitution Principle:里氏替换原则
  • Law of Demeter:迪米特法则
  • Interface Segregation Principle:接口隔离原则
  • Dependence Inversion Principle:依赖倒置原则

把这六个原则的首字母联合起来(两个 L 算做一个)就是 SOLID (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.  
  12.     render(data); 
  13.   }); 
  14.  
  15. function showManagerList(managers) { 
  16.   managers.forEach(manager => { 
  17.     const expectedSalary = manager.calculateExpectedSalary(); 
  18.     const experience = manager.getExperience(); 
  19.     const portfolio = manager.getMBAProjects(); 
  20.     const data = { 
  21.       expectedSalary, 
  22.       experience, 
  23.       portfolio 
  24.     }; 
  25.  
  26.     render(data); 
  27.   }); 

「好的写法」

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

使用Object.assign设置默认对象

「不好的写法」

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

「好的写法」

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

不要使用标志作为函数参数

标志告诉使用者,此函数可以完成多项任务,函数应该做一件事。如果函数遵循基于布尔的不同代码路径,请拆分它们。

  1. // 不好的写法 
  2. function createFile(name, temp) { 
  3.   if (temp) { 
  4.     fs.create(`./temp/${name}`); 
  5.   } else { 
  6.     fs.create(name); 
  7.   } 
  8.  
  9. // 好的写法 
  10. function createFile(name) { 
  11.   fs.create(name); 
  12.  
  13. function createTempFile(name) { 
  14.   createFile(`./temp/${name}`); 

避免副作用(第一部分)

如果函数除了接受一个值并返回另一个值或多个值以外,不执行任何其他操作,都会产生副作用。副作用可能是写入文件,修改某些全局变量,或者不小心将你的所有资金都汇给了陌生人。

「不好的写法」

  1. let name = "Ryan McDermott"
  2.  
  3. function splitIntoFirstAndLastName() { 
  4.   namename = name.split(" "); 
  5.  
  6. splitIntoFirstAndLastName(); 
  7.  
  8. 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.  
  7. console.log(name); // 'Ryan McDermott'; 
  8. console.log(newName); // ['Ryan', 'McDermott']; 

避免副作用(第二部分)

在JavaScript中,原始类型值是按值传递,而对象/数组按引用传递。对于对象和数组,如果有函数在购物车数组中进行了更改(例如,通过添加要购买的商品),则使用该购物车数组的任何其他函数都将受到此添加的影响。那可能很棒,但是也可能不好。来想象一个糟糕的情况:

用户单击“购买”按钮,该按钮调用一个purchase 函数,接着,该函数发出一个网络请求并将cart数组发送到服务器。由于网络连接不好,purchase函数必须不断重试请求。现在,如果在网络请求开始之前,用户不小心点击了他们实际上不需要的项目上的“添加到购物车”按钮,该怎么办?如果发生这种情况,并且网络请求开始,那么购买函数将发送意外添加的商品,因为它有一个对购物车数组的引用,addItemToCart函数通过添加修改了这个购物车数组。

一个很好的解决方案是addItemToCart总是克隆cart数组,编辑它,然后返回克隆。这可以确保购物车引用的其他函数不会受到任何更改的影响。

关于这种方法有两点需要注意:

  • 可能在某些情况下,我们确实需要修改输入对象,但是当我们采用这种编程实践时,会发现这种情况非常少见,大多数东西都可以被改造成没有副作用。
  • 就性能而言,克隆大对象可能会非常昂贵。幸运的是,在实践中这并不是一个大问题,因为有很多很棒的库使这种编程方法能够快速进行,并且不像手动克隆对象和数组那样占用大量内存。
  1. // 不好的写法 
  2. const addItemToCart = (cart, item) => { 
  3.   cart.push({ item, date: Date.now() }); 
  4. }; 
  5.  
  6. // 好的写法 
  7. const addItemToCart = (cart, item) => { 
  8.   return [...cart, { item, date: Date.now() }]; 
  9. }; 

不要写全局函数

污染全局变量在 JS 中是一种不好的做法,因为可能会与另一个库发生冲突,并且在他们的生产中遇到异常之前,API 的用户将毫无用处。让我们考虑一个示例:如果想扩展 JS 的原生Array方法以具有可以显示两个数组之间差异的diff方法,该怎么办?可以将新函数写入Array.prototype,但它可能与另一个尝试执行相同操作的库发生冲突。如果其他库仅使用diff来查找数组的第一个元素和最后一个元素之间的区别怎么办?这就是为什么只使用 ES6 类并简单地扩展Array全局会更好的原因。

  1. // 不好的写法 
  2. Array.prototype.diff = function diff(comparisonArray) { 
  3.   const hash = new Set(comparisonArray); 
  4.   return this.filter(elem => !hash.has(elem)); 
  5. }; 
  6.  
  7. // 好的写法 
  8. class SuperArray extends Array { 
  9.   diff(comparisonArray) { 
  10.     const hash = new Set(comparisonArray); 
  11.     return this.filter(elem => !hash.has(elem)); 
  12.   } 

尽量使用函数式编程而非命令式

JavaScript不像Haskell那样是一种函数式语言,但它具有函数式的风格。函数式语言可以更简洁、更容易测试。如果可以的话,尽量喜欢这种编程风格。

「不好的写法」

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

「好的写法」

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

封装条件

  1. // 不好的写法 
  2. if (fsm.state === "fetching" && isEmpty(listNode)) { 
  3.   // ... 
  4.  
  5. // 好的写法 
  6. function shouldShowSpinner(fsm, listNode) { 
  7.   return fsm.state === "fetching" && isEmpty(listNode); 
  8.  
  9. if (shouldShowSpinner(fsmInstance, listNodeInstance)) { 
  10.   // ... 

避免使用非条件

  1. // 不好的写法 
  2. function isDOMNodeNotPresent(node) { 
  3.   // ... 
  4.  
  5. if (!isDOMNodeNotPresent(node)) { 
  6.   // ... 
  7.  
  8. // 好的写法 
  9. function isDOMNodePresent(node) { 
  10.   // ... 
  11.  
  12. if (isDOMNodePresent(node)) { 
  13.   // ... 

避免使用过多条件

这似乎是一个不可能完成的任务。一听到这个,大多数人会说,“没有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.   } 

「好的写法」

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

避免类型检查

JavaScript 是无类型的,这意味着函数可以接受任何类型的参数。有时q我们会被这种自由所困扰,并且很想在函数中进行类型检查。有很多方法可以避免这样做。首先要考虑的是一致的API。

  1. // 不好的写法 
  2. function travelToTexas(vehicle) { 
  3.   if (vehicle instanceof Bicycle) { 
  4.     vehicle.pedal(this.currentLocation, new Location("texas")); 
  5.   } else if (vehicle instanceof Car) { 
  6.     vehicle.drive(this.currentLocation, new Location("texas")); 
  7.   } 
  8.  
  9. // 好的写法 
  10. function travelToTexas(vehicle) { 
  11.   vehicle.move(this.currentLocation, new Location("texas")); 

不要过度优化

现代浏览器在运行时做了大量的优化工作。很多时候,如果你在优化,那么你只是在浪费时间。有很好的资源可以查看哪里缺乏优化,我们只需要针对需要优化的地方就行了。

  1. // 不好的写法 
  2.  
  3. // 在旧的浏览器上,每一次使用无缓存“list.length”的迭代都是很昂贵的 
  4. // 会为“list.length”重新计算。在现代浏览器中,这是经过优化的 
  5. for (let i = 0len = list.length; i < len; i++) { 
  6.   // ... 
  7.  
  8. // 好的写法 
  9. for (let i = 0; i < list.length; i++) { 
  10.   // ... 

 

责任编辑:赵宁宁 来源: 大迁世界
相关推荐

2020-05-14 09:15:52

设计模式SOLID 原则JS

2021-01-04 07:57:07

C++工具代码

2019-09-20 15:47:24

代码JavaScript副作用

2022-03-11 12:14:43

CSS代码前端

2021-12-07 08:16:34

React 前端 组件

2017-08-10 14:55:33

前端JavaScript 函数

2020-07-15 08:17:16

代码

2013-06-07 14:00:23

代码维护

2020-05-11 15:23:58

CQRS代码命令

2021-09-01 08:55:20

JavaScript代码开发

2021-11-30 10:20:24

JavaScript代码前端

2022-02-17 10:05:21

CSS代码前端

2022-02-08 19:33:13

技巧代码格式

2020-12-19 10:45:08

Python代码开发

2020-05-19 15:00:26

Bug代码语言

2021-12-13 14:37:37

React组件前端

2022-10-24 08:10:21

SQL代码业务

2019-06-24 10:26:15

代码程序注释

2015-09-28 10:49:59

代码程序员

2015-05-11 10:48:28

代码干净的代码越少越干净
点赞
收藏

51CTO技术栈公众号