自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何寫出干凈的 JavaScript 代碼

開發(fā) 前端
編寫干凈的代碼非常重要,因?yàn)樵谖覀內(nèi)粘5墓ぷ髦?,你不是僅僅是在為自己寫代碼。實(shí)際上,你還需要考慮一群需要理解、編輯和構(gòu)建你的代碼的同事。

一段干凈的代碼,你在閱讀、重用和重構(gòu)的時(shí)候都能非常輕松。編寫干凈的代碼非常重要,因?yàn)樵谖覀內(nèi)粘5墓ぷ髦校悴皇莾H僅是在為自己寫代碼。實(shí)際上,你還需要考慮一群需要理解、編輯和構(gòu)建你的代碼的同事。

[[420840]]

1. 變量使用有意義的名稱

變量的名稱應(yīng)該是可描述,有意義的, JavaScript 變量都應(yīng)該采用駝峰式大小寫 ( 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) 避免添加不必要的上下文

當(dāng)對(duì)象或類已經(jīng)包含了上下文的命名時(shí),不要再向變量名稱添加冗余的上下文。

  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) 避免硬編碼值

確保聲明有意義且可搜索的常量,而不是直接插入一個(gè)常量值。全局常量可以采用 SCREAMING_SNAKE_CASE 風(fēng)格命名。

  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. 函數(shù)使用有意義的名稱

函數(shù)名稱需要描述函數(shù)的實(shí)際作用,即使很長(zhǎng)也沒關(guān)系。函數(shù)名稱通常使用動(dòng)詞,但返回布爾值的函數(shù)可能是個(gè)例外 — 它可以采用 是或否 問題的形式,函數(shù)名也應(yīng)該是駝峰式的。

  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) 使用默認(rèn)參數(shù)

默認(rèn)參數(shù)比 && || 或在函數(shù)體內(nèi)使用額外的條件語句更干凈。

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

(2) 限制參數(shù)的數(shù)量

盡管這條規(guī)則可能有爭(zhēng)議,但函數(shù)最好是有3個(gè)以下參數(shù)。如果參數(shù)較多可能是以下兩種情況之一:

  • 該函數(shù)做的事情太多,應(yīng)該拆分。
  • 傳遞給函數(shù)的數(shù)據(jù)以某種方式相關(guān),可以作為專用數(shù)據(jù)結(jié)構(gòu)傳遞。
  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) 避免在一個(gè)函數(shù)中做太多事情

一個(gè)函數(shù)應(yīng)該一次做一件事,這有助于減少函數(shù)的大小和復(fù)雜性,使測(cè)試、調(diào)試和重構(gòu)更容易。

  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) 避免使用布爾標(biāo)志作為參數(shù)

函數(shù)含有布爾標(biāo)志的參數(shù)意味這個(gè)函數(shù)是可以被簡(jiǎn)化的。

  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) 避免寫重復(fù)的代碼

如果你寫了重復(fù)的代碼,每次有邏輯改變,你都需要改動(dòng)多個(gè)位置。

  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 中,你應(yīng)該更喜歡函數(shù)式模式而不是命令式模式。換句話說,大多數(shù)情況下我們都應(yīng)該保持函數(shù)純。副作用可能會(huì)修改共享狀態(tài)和資源,從而導(dǎo)致一些奇怪的問題。所有的副作用都應(yīng)該集中管理,例如你需要更改全局變量或修改文件,可以專門寫一個(gè) 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']; 

另外,如果你將一個(gè)可變值傳遞給函數(shù),你應(yīng)該直接克隆一個(gè)新值返回,而不是直接改變?cè)撍?/p>

  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) 使用非負(fù)條件

  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) 盡可能使用簡(jiǎn)寫

  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 會(huì)使你的代碼線性化、更具可讀性且不那么復(fù)雜。

  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) 優(yōu)先使用 map 而不是 switch 語句

既能減少復(fù)雜度又能提升性能。

  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. 并發(fā)

避免回調(diào):

回調(diào)很混亂,會(huì)導(dǎo)致代碼嵌套過深,使用 Promise 替代回調(diào)。

  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. 錯(cuò)誤處理

處理拋出的錯(cuò)誤和 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) 只注釋業(yè)務(wù)邏輯

可讀的代碼使你免于過度注釋,因此,你應(yīng)該只注釋復(fù)雜的邏輯。

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

好了,去寫出你漂亮的代碼吧!

 

責(zé)任編輯:趙寧寧 來源: code秘密花園
相關(guān)推薦

2021-11-30 10:20:24

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

開發(fā)代碼技巧

2020-05-11 15:23:58

CQRS代碼命令

2013-06-07 14:00:23

代碼維護(hù)

2022-06-07 09:30:35

JavaScript變量名參數(shù)

2021-01-04 07:57:07

C++工具代碼

2022-02-08 19:33:13

技巧代碼格式

2022-02-17 10:05:21

CSS代碼前端

2020-12-19 10:45:08

Python代碼開發(fā)

2020-05-19 15:00:26

Bug代碼語言

2022-03-11 12:14:43

CSS代碼前端

2022-10-24 08:10:21

SQL代碼業(yè)務(wù)

2015-09-28 10:49:59

代碼程序員

2019-06-24 10:26:15

代碼程序注釋

2020-05-14 09:15:52

設(shè)計(jì)模式SOLID 原則JS

2021-07-19 08:24:36

阿里代碼程序員

2022-06-16 14:07:26

Java代碼代碼review
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)