如何写出干净的 JavaScript 代码

开发 前端
一段干净的代码,你在阅读、重用和重构的时候都能非常轻松。编写干净的代码非常重要,因为在我们日常的工作中,你不是仅仅是在为自己写代码。

 [[437569]]

一段干净的代码,你在阅读、重用和重构的时候都能非常轻松。编写干净的代码非常重要,因为在我们日常的工作中,你不是仅仅是在为自己写代码。实际上,你还需要考虑一群需要理解、编辑和构建你的代码的同事。

1. 变量

使用有意义的名称

变量的名称应该是可描述,有意义的, JavaScript 变量都应该采用驼峰式大小写 ( camelCase) 命名。 

  1. // Don't ❌  
  2. const foo = "JDoe@example.com" 
  3. const bar = "John" 
  4. const age = 23 
  5. const qux = true 
  6. // Do ✅  
  7. const email = "John@example.com" 
  8. const firstName = "John" 
  9. const age = 23 
  10. const isActive = true 

布尔变量通常需要回答特定问题,例如: 

  1. isActive   
  2. didSubscribe   
  3. hasLinkedAccount 

避免添加不必要的上下文

当对象或类已经包含了上下文的命名时,不要再向变量名称添加冗余的上下文。 

  1. // Don't ❌  
  2. const user = {  
  3.   userId: "296e2589-7b33-400a-b762-007b730c8e6d",  
  4.   userEmail: "JDoe@example.com",  
  5.   userFirstName: "John",  
  6.   userLastName: "Doe",  
  7.   userAge: 23,  
  8. };  
  9. user.userId;  
  10. // Do ✅  
  11. const user = {  
  12.   id: "296e2589-7b33-400a-b762-007b730c8e6d",  
  13.   email: "JDoe@example.com",  
  14.   firstName: "John",  
  15.   lastName: "Doe",  
  16.   age: 23,  
  17. };  
  18. user.id; 

避免硬编码值

确保声明有意义且可搜索的常量,而不是直接插入一个常量值。全局常量可以采用 SCREAMING_SNAKE_CASE 风格命名。 

  1. // Don't ❌  
  2. setTimeout(clearSessionData, 900000);  
  3. // Do ✅  
  4. const SESSION_DURATION_MS = 15 * 60 * 1000;  
  5. setTimeout(clearSessionData, SESSION_DURATION_MS); 

2. 函数

使用有意义的名称

函数名称需要描述函数的实际作用,即使很长也没关系。函数名称通常使用动词,但返回布尔值的函数可能是个例外 — 它可以采用 是或否 问题的形式,函数名也应该是驼峰式的。 

  1. // Don't ❌  
  2. function toggle() {  
  3.   // ...  
  4.  
  5. function agreed(user) {  
  6.   // ...  
  7.  
  8. // Do ✅  
  9. function toggleThemeSwitcher() {  
  10.   // ...  
  11.  
  12. function didAgreeToAllTerms(user) {  
  13.   // ...  

使用默认参数

默认参数比 && || 或在函数体内使用额外的条件语句更干净。 

  1. // Don't ❌  
  2. function printAllFilesInDirectory(dir) {  
  3.   const dirdirectory = dir || "./";  
  4.   //   ...  
  5.  
  6. // Do ✅  
  7. function printAllFilesInDirectory(dir = "./") {  
  8.   // ...  

限制参数的数量

尽管这条规则可能有争议,但函数最好是有3个以下参数。如果参数较多可能是以下两种情况之一:

  •  该函数做的事情太多,应该拆分。
  •  传递给函数的数据以某种方式相关,可以作为专用数据结构传递。 
  1. // Don't ❌  
  2. function sendPushNotification(title, message, image, isSilent, delayMs) {  
  3.   // ...  
  4.  
  5. sendPushNotification("New Message", "...", "http://...", false, 1000);  
  6. // Do ✅  
  7. function sendPushNotification({ title, message, image, isSilent, delayMs }) {  
  8.   // ...  
  9.  
  10. const notificationConfig = {  
  11.   title: "New Message",  
  12.   message: "...",  
  13.   image: "http://...",  
  14.   isSilent: false,  
  15.   delayMs: 1000,  
  16. };  
  17. sendPushNotification(notificationConfig); 

避免在一个函数中做太多事情

一个函数应该一次做一件事,这有助于减少函数的大小和复杂性,使测试、调试和重构更容易。 

  1. / Don't ❌  
  2. function pingUsers(users) {  
  3.   users.forEach((user) => {  
  4.     const userRecord = database.lookup(user);  
  5.     if (!userRecord.isActive()) {  
  6.       ping(user);  
  7.     }  
  8.   });  
  9.  
  10. // Do ✅  
  11. function pingInactiveUsers(users) {  
  12.   users.filter(!isUserActive).forEach(ping);  
  13.  
  14. function isUserActive(user) {  
  15.   const userRecord = database.lookup(user);  
  16.   return userRecord.isActive(); 
  17.  

避免使用布尔标志作为参数

函数含有布尔标志的参数意味这个函数是可以被简化的。 

  1. // Don't ❌  
  2. function createFile(name, isPublic) {  
  3.   if (isPublic) {  
  4.     fs.create(`./public/${name}`);  
  5.   } else {  
  6.     fs.create(name);  
  7.   }  
  8.  
  9. // Do ✅  
  10. function createFile(name) {  
  11.   fs.create(name);  
  12.  
  13. function createPublicFile(name) {  
  14.   createFile(`./public/${name}`);  

避免写重复的代码

如果你写了重复的代码,每次有逻辑改变,你都需要改动多个位置。 

  1. // Don't ❌  
  2. function renderCarsList(cars) {  
  3.   cars.forEach((car) => {  
  4.     const price = car.getPrice();  
  5.     const make = car.getMake();  
  6.     const brand = car.getBrand();  
  7.     const nbOfDoors = car.getNbOfDoors();  
  8.     render({ price, make, brand, nbOfDoors });  
  9.   });  
  10.  
  11. function renderMotorcyclesList(motorcycles) {  
  12.   motorcycles.forEach((motorcycle) => {  
  13.     const price = motorcycle.getPrice();  
  14.     const make = motorcycle.getMake();  
  15.     const brand = motorcycle.getBrand();  
  16.     const seatHeight = motorcycle.getSeatHeight();  
  17.     render({ price, make, brand, nbOfDoors });  
  18.   });  
  19.  
  20. // Do ✅  
  21. function renderVehiclesList(vehicles) {  
  22.   vehicles.forEach((vehicle) => {  
  23.     const price = vehicle.getPrice();  
  24.     const make = vehicle.getMake();  
  25.     const brand = vehicle.getBrand();  
  26.     const data = { price, make, brand };  
  27.     switch (vehicle.type) {  
  28.       case "car":  
  29.         data.nbOfDoors = vehicle.getNbOfDoors();  
  30.         break;  
  31.       case "motorcycle":  
  32.         data.seatHeight = vehicle.getSeatHeight();  
  33.         break;  
  34.     }  
  35.     render(data);  
  36.   });  

避免副作用

在 JavaScript 中,你应该更喜欢函数式模式而不是命令式模式。换句话说,大多数情况下我们都应该保持函数纯。副作用可能会修改共享状态和资源,从而导致一些奇怪的问题。所有的副作用都应该集中管理,例如你需要更改全局变量或修改文件,可以专门写一个 util 来做这件事。 

  1. // Don't ❌  
  2. let date = "21-8-2021" 
  3. function splitIntoDayMonthYear() {  
  4.   datedate = date.split("-");  
  5.  
  6. splitIntoDayMonthYear();  
  7. // Another function could be expecting date as a string  
  8. console.log(date); // ['21', '8', '2021'];  
  9. // Do ✅  
  10. function splitIntoDayMonthYear(date) {  
  11.   return date.split("-");  
  12.  
  13. const date = "21-8-2021" 
  14. const newDate = splitIntoDayMonthYear(date);  
  15. // Original vlaue is intact  
  16. console.log(date); // '21-8-2021';  
  17. console.log(newDate); // ['21', '8', '2021']; 

另外,如果你将一个可变值传递给函数,你应该直接克隆一个新值返回,而不是直接改变该它。

 

  1. // Don't ❌  
  2. function enrollStudentInCourse(course, student) {  
  3.   course.push({ student, enrollmentDate: Date.now() }); 
  4.  
  5. // Do ✅  
  6. function enrollStudentInCourse(course, student) {  
  7.   return [...course, { student, enrollmentDate: Date.now() }];  

3. 条件语句

使用非负条件 

  1. // Don't ❌  
  2. function isUserNotVerified(user) {  
  3.   // ...  
  4.  
  5. if (!isUserNotVerified(user)) {  
  6.   // ...  
  7.  
  8. // Do ✅  
  9. function isUserVerified(user) {  
  10.   // ...  
  11.  
  12. if (isUserVerified(user)) {  
  13.   // ...  

尽可能使用简写 

  1. // Don't ❌  
  2. if (isActive === true) {  
  3.   // ...  
  4.  
  5. if (firstName !== "" && firstName !== null && firstName !== undefined) {  
  6.   // ...  
  7.  
  8. const isUserEligible = user.isVerified() && user.didSubscribe() ? true : false;  
  9. // Do ✅  
  10. if (isActive) {  
  11.   // ...  
  12.  
  13. if (!!firstName) {  
  14.   // ...  
  15.  
  16. const isUserEligible = user.isVerified() && user.didSubscribe(); 

避免过多分支

尽早 return 会使你的代码线性化、更具可读性且不那么复杂。 

  1. // Don't ❌  
  2. function addUserService(db, user) {  
  3.   if (!db) {  
  4.     if (!db.isConnected()) {  
  5.       if (!user) {  
  6.         return db.insert("users", user);  
  7.       } else {  
  8.         throw new Error("No user");  
  9.       }  
  10.     } else {  
  11.       throw new Error("No database connection");  
  12.     }  
  13.   } else {  
  14.     throw new Error("No database");  
  15.   }  
  16.  
  17. // Do ✅  
  18. function addUserService(db, user) {  
  19.   if (!db) throw new Error("No database");  
  20.   if (!db.isConnected()) throw new Error("No database connection");  
  21.   if (!user) throw new Error("No user");  
  22.   return db.insert("users", user);  

优先使用 map 而不是 switch 语句

既能减少复杂度又能提升性能。 

  1. // Don't ❌  
  2. const getColorByStatus = (status) => {  
  3.   switch (status) {  
  4.     case "success":  
  5.       return "green";  
  6.     case "failure":  
  7.       return "red";  
  8.     case "warning":  
  9.       return "yellow";  
  10.     case "loading":  
  11.     default:  
  12.       return "blue";  
  13.   }  
  14. };  
  15. // Do ✅  
  16. const statusColors = {  
  17.   success: "green",  
  18.   failure: "red",  
  19.   warning: "yellow",  
  20.   loading: "blue",  
  21. };  
  22. const getColorByStatus = (status) => statusColors[status] || "blue"; 

使用可选链接 

  1. const user = {  
  2.   email: "JDoe@example.com",  
  3.   billing: {  
  4.     iban: "...",  
  5.     swift: "...",  
  6.     address: {  
  7.       street: "Some Street Name",  
  8.       state: "CA",  
  9.     }, 
  10.   },  
  11. };  
  12. // Don't ❌  
  13. const email = (user && user.email) || "N/A";  
  14. const street =  
  15.   (user &&  
  16.     user.billing &&  
  17.     user.billing.address &&  
  18.     user.billing.address.street) ||  
  19.   "N/A";  
  20. const state =  
  21.   (user &&  
  22.     user.billing &&  
  23.     user.billing.address &&  
  24.     user.billing.address.state) ||  
  25.   "N/A";  
  26. // Do ✅  
  27. const email = user?.email ?? "N/A";  
  28. const street = user?.billing?.address?.street ?? "N/A";  
  29. const street = user?.billing?.address?.state ?? "N/A"; 

4.并发

避免回调

回调很混乱,会导致代码嵌套过深,使用 Promise 替代回调。 

  1. // Don't ❌  
  2. getUser(function (err, user) {  
  3.   getProfile(user, function (err, profile) {  
  4.     getAccount(profile, function (err, account) {  
  5.       getReports(account, function (err, reports) {  
  6.         sendStatistics(reports, function (err) {  
  7.           console.error(err);  
  8.         });  
  9.       });  
  10.     });  
  11.   });  
  12. });  
  13. // Do ✅  
  14. getUser()  
  15.   .then(getProfile)  
  16.   .then(getAccount)  
  17.   .then(getReports)  
  18.   .then(sendStatistics)  
  19.   .catch((err) => console.error(err));  
  20. // or using Async/Await ✅✅  
  21. async function sendUserStatistics() {  
  22.   try {  
  23.     const user = await getUser();  
  24.     const profile = await getProfile(user);  
  25.     const account = await getAccount(profile);  
  26.     const reports = await getReports(account);  
  27.     return sendStatistics(reports);  
  28.   } catch (e) {  
  29.     console.error(err);  
  30.   }  

5. 错误处理

处理抛出的错误和 reject 的 promise 

  1. / Don't ❌  
  2. try {  
  3.   // Possible erronous code  
  4. } catch (e) {  
  5.   console.log(e);  
  6.  
  7. // Do ✅  
  8. try {  
  9.   // Possible erronous code  
  10. } catch (e) {  
  11.   // Follow the most applicable (or all):  
  12.   // 1- More suitable than console.log  
  13.   console.error(e);  
  14.   // 2- Notify user if applicable  
  15.   alertUserOfError(e);  
  16.   // 3- Report to server  
  17.   reportErrorToServer(e);  
  18.   // 4- Use a custom error handler  
  19.   throw new CustomError(e);  

6.注释

只注释业务逻辑

可读的代码使你免于过度注释,因此,你应该只注释复杂的逻辑。 

  1. // Don't ❌  
  2. function generateHash(str) {  
  3.   // Hash variable  
  4.   let hash = 0 
  5.   // Get the length of the string  
  6.   let length = str.length;  
  7.   // If the string is empty return  
  8.   if (!length) {  
  9.     return hash;  
  10.   }  
  11.   // Loop through every character in the string  
  12.   for (let i = 0; i < length; i++) {  
  13.     // Get character code.  
  14.     const char = str.charCodeAt(i);  
  15.     // Make the hash  
  16.     hash = (hash << 5) - hash + char;  
  17.     // Convert to 32-bit integer  
  18.     hash &= hash;  
  19.   }  
  20.  
  21. // Do ✅ 
  22.  function generateHash(str) {  
  23.   let hash = 0 
  24.   let length = str.length;  
  25.   if (!length) {  
  26.     return hash;  
  27.   }  
  28.   for (let i = 0; i < length; i++) {  
  29.     const char = str.charCodeAt(i);  
  30.     hash = (hash << 5) - hash + char;  
  31.     hashhash = hash & hash; // Convert to 32bit integer  
  32.   }  
  33.   return hash;  

使用版本控制

在代码里不需要保留历史版本的注释,想查的话你直接用 git log 就可以搜到。 

  1. // Don't ❌  
  2. /**  
  3.  * 2021-7-21: Fixed corner case  
  4.  * 2021-7-15: Improved performance  
  5.  * 2021-7-10: Handled mutliple user types  
  6.  */  
  7. function generateCanonicalLink(user) {  
  8.   // const session = getUserSession(user)  
  9.   const session = user.getSession();  
  10.   // ...  
  11.  
  12. // Do ✅  
  13. function generateCanonicalLink(user) {  
  14.   const session = user.getSession();  
  15.   // ...  

好了,去写出你漂亮的代码吧!🌈 

 

责任编辑:庞桂玉 来源: 前端大全
相关推荐

2021-09-01 08:55:20

JavaScript代码开发

2015-05-11 10:48:28

代码干净的代码越少越干净

2019-09-20 15:47:24

代码JavaScript副作用

2020-07-15 08:17:16

代码

2020-05-27 10:38:16

开发代码技巧

2013-06-07 14:00:23

代码维护

2020-05-11 15:23:58

CQRS代码命令

2022-06-07 09:30:35

JavaScript变量名参数

2022-02-17 10:05:21

CSS代码前端

2022-02-08 19:33:13

技巧代码格式

2021-01-04 07:57:07

C++工具代码

2020-12-19 10:45:08

Python代码开发

2020-05-19 15:00:26

Bug代码语言

2022-03-11 12:14:43

CSS代码前端

2022-10-24 08:10:21

SQL代码业务

2015-09-28 10:49:59

代码程序员

2019-06-24 10:26:15

代码程序注释

2022-06-16 14:07:26

Java代码代码review

2021-07-19 08:24:36

阿里代码程序员

2020-05-14 09:15:52

设计模式SOLID 原则JS
点赞
收藏

51CTO技术栈公众号