如何写出干净的 JavaScript 代码

时间:2021-08-23 02:00:40

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

如何写出干净的 JavaScript 代码

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.  
  7. // Do 
  8. const email = "John@example.com"
  9. const firstName = "John"
  10. const age = 23
  11. const isActive = true 

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

  1. isActive  
  2. didSubscribe  
  3. hasLinkedAccount 

(1) 避免添加不必要的上下文

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

  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.  
  10. user.userId; 
  11.  
  12. // Do 
  13. const user = { 
  14.   id: "296e2589-7b33-400a-b762-007b730c8e6d", 
  15.   email: "JDoe@example.com", 
  16.   firstName: "John", 
  17.   lastName: "Doe", 
  18.   age: 23, 
  19. }; 

(2) 避免硬编码值

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

  1. // Don't  
  2. setTimeout(clearSessionData, 900000); 
  3.  
  4. // Do 
  5. const SESSION_DURATION_MS = 15 * 60 * 1000; 
  6.  
  7. 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) 使用默认参数

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

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

(2) 限制参数的数量

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

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

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

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

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

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

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

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

(5) 避免写重复的代码

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

  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.  
  9.     render({ price, make, brand, nbOfDoors }); 
  10.   }); 
  11.  
  12. function renderMotorcyclesList(motorcycles) { 
  13.   motorcycles.forEach((motorcycle) => { 
  14.     const price = motorcycle.getPrice(); 
  15.     const make = motorcycle.getMake(); 
  16.     const brand = motorcycle.getBrand(); 
  17.     const seatHeight = motorcycle.getSeatHeight(); 
  18.  
  19.     render({ price, make, brand, nbOfDoors }); 
  20.   }); 
  21.  
  22. // Do 
  23. function renderVehiclesList(vehicles) { 
  24.   vehicles.forEach((vehicle) => { 
  25.     const price = vehicle.getPrice(); 
  26.     const make = vehicle.getMake(); 
  27.     const brand = vehicle.getBrand(); 
  28.  
  29.     const data = { price, make, brand }; 
  30.  
  31.     switch (vehicle.type) { 
  32.       case "car": 
  33.         data.nbOfDoors = vehicle.getNbOfDoors(); 
  34.         break; 
  35.       case "motorcycle": 
  36.         data.seatHeight = vehicle.getSeatHeight(); 
  37.         break; 
  38.     } 
  39.  
  40.     render(data); 
  41.   }); 

(6) 避免副作用

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

  1. // Don't  
  2. let date = "21-8-2021"
  3.  
  4. function splitIntoDayMonthYear() { 
  5.   datedate = date.split("-"); 
  6.  
  7. splitIntoDayMonthYear(); 
  8.  
  9. // Another function could be expecting date as a string 
  10. console.log(date); // ['21', '8', '2021']; 
  11.  
  12. // Do 
  13. function splitIntoDayMonthYear(date) { 
  14.   return date.split("-"); 
  15.  
  16. const date = "21-8-2021"
  17. const newDate = splitIntoDayMonthYear(date); 
  18.  
  19. // Original vlaue is intact 
  20. console.log(date); // '21-8-2021'; 
  21. 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) 使用非负条件

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

(2) 尽可能使用简写

  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.  
  10. // Do 
  11. if (isActive) { 
  12.   // ... 
  13.  
  14. if (!!firstName) { 
  15.   // ... 
  16.  
  17. const isUserEligible = user.isVerified() && user.didSubscribe(); 

(3) 避免过多分支

尽早 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.  
  23.   return db.insert("users", user); 

(4) 优先使用 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.  
  16. // Do 
  17. const statusColors = { 
  18.   success: "green", 
  19.   failure: "red", 
  20.   warning: "yellow", 
  21.   loading: "blue", 
  22. }; 
  23.  
  24. const getColorByStatus = (status) => statusColors[status] || "blue"; 

(5) 使用可选链接

  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.  
  13. // Don't  
  14. const email = (user && user.email) || "N/A"; 
  15. const street = 
  16.   (user && 
  17.     user.billing && 
  18.     user.billing.address && 
  19.     user.billing.address.street) || 
  20.   "N/A"; 
  21. const state = 
  22.   (user && 
  23.     user.billing && 
  24.     user.billing.address && 
  25.     user.billing.address.state) || 
  26.   "N/A"; 
  27.  
  28. // Do 
  29. const email = user?.email ?? "N/A"; 
  30. const street = user?.billing?.address?.street ?? "N/A"; 
  31. 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.  
  14. // Do 
  15. getUser() 
  16.   .then(getProfile) 
  17.   .then(getAccount) 
  18.   .then(getReports) 
  19.   .then(sendStatistics) 
  20.   .catch((err) => console.error(err)); 
  21.  
  22. // or using Async/Await ✅
  23.  
  24. async function sendUserStatistics() { 
  25.   try { 
  26.     const user = await getUser(); 
  27.     const profile = await getProfile(user); 
  28.     const account = await getAccount(profile); 
  29.     const reports = await getReports(account); 
  30.     return sendStatistics(reports); 
  31.   } catch (e) { 
  32.     console.error(err); 
  33.   } 

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.  
  15.   // 2- Notify user if applicable 
  16.   alertUserOfError(e); 
  17.  
  18.   // 3- Report to server 
  19.   reportErrorToServer(e); 
  20.  
  21.   // 4- Use a custom error handler 
  22.   throw new CustomError(e); 

6. 注释

(1) 只注释业务逻辑

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

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

(2) 使用版本控制

在代码里不需要保留历史版本的注释,想查的话你直接用 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.   // ... 

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

原文链接:https://mp.weixin.qq.com/s?__biz=Mzg2NDAzMjE5NQ==&mid=2247491031&idx=1&sn=fa42efdc0e5af8fc11888d5bd3337cf6&chksm=ce6ed97bf919506d2b0703fc0b4004dca9135012ed5babf2cf72c95082301338e3261bd5bc99&mpshare=1&s

相关文章