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

如何寫出干凈的 JavaScript 代碼

開發(fā) 前端
一段干凈的代碼,你在閱讀、重用和重構(gòu)的時候都能非常輕松。編寫干凈的代碼非常重要,因?yàn)樵谖覀內(nèi)粘5墓ぷ髦校悴皇莾H僅是在為自己寫代碼。

 [[437569]]

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

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

避免添加不必要的上下文

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

  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 風(fēng)格命名。 

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

2. 函數(shù)

使用有意義的名稱

函數(shù)名稱需要描述函數(shù)的實(shí)際作用,即使很長也沒關(guān)系。函數(shù)名稱通常使用動詞,但返回布爾值的函數(shù)可能是個例外 — 它可以采用 是或否 問題的形式,函數(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.   // ...  

使用默認(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.   // ...  

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

盡管這條規(guī)則可能有爭議,但函數(shù)最好是有3個以下參數(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. // 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); 

避免在一個函數(shù)中做太多事情

一個函數(shù)應(yīng)該一次做一件事,這有助于減少函數(shù)的大小和復(fù)雜性,使測試、調(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(); 
  17.  

避免使用布爾標(biāo)志作為參數(shù)

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

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

避免寫重復(fù)的代碼

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

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

另外,如果你將一個可變值傳遞給函數(shù),你應(yīng)該直接克隆一個新值返回,而不是直接改變該它。

 

  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. 條件語句

使用非負(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.   // ...  

盡可能使用簡寫 

  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 會使你的代碼線性化、更具可讀性且不那么復(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.   return db.insert("users", user);  

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

避免回調(diào)

回調(diào)很混亂,會導(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. // 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.注釋

只注釋業(yè)務(wù)邏輯

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

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

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

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2021-09-01 08:55:20

JavaScript代碼開發(fā)

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代碼前端

2022-03-11 12:14:43

CSS代碼前端

2020-12-19 10:45:08

Python代碼開發(fā)

2020-05-19 15:00:26

Bug代碼語言

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ù)棧公眾號