加入收藏 | 设为首页 | 会员中心 | 我要投稿 晋中站长网 (https://www.0354zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

重构的艺术:五个小妙招助你写出好代码!

发布时间:2019-11-06 07:09:33 所属栏目:优化 来源:读芯术
导读:糟糕的代码可以运作,但早晚会让我们付出代价。你有没有遇到过这样的问题:几周后,你无法理解自己的代码,于是不得不花上几个小时,甚至几天的时间来弄清楚到底发生了什么。 解决这个常见问题的方法是使代码尽可能清晰。如果做得更好的话,即使是非技术人

如你所见,这让人困惑,也很难理解里面发生了什么。如果有错误出现,都很难找到并修复它们。如何改进startProgram函数?可以将公共逻辑提取到函数中。以下是具体操作方法:

  1. function startProgram() { 
  2.   if (!window.indexedDB) { 
  3.     throw new Error("Browser doesn't support indexedDB"); 
  4.   } 
  5.  
  6.   initDatabase(); 
  7.   setListeners(); 
  8.   printEmployeeList(); 
  9.  
  10. function initDatabase() { 
  11.   let openRequest = indexedDB.open('store', 1); 
  12.  
  13.   openRequest.onerror = () => { 
  14.     console.error('Error', openRequest.error); 
  15.   }; 
  16.   openRequest.onsuccess = () => { 
  17.     let db = openRequest.result; 
  18.   }; 
  19.  
  20. function setListeners() { 
  21.   document.getElementById('stat-op').addEventListener('click', () => {}); 
  22.   document.getElementById('pre2456').addEventListener('click', () => {}); 
  23.   document.getElementById('cpTagList100').addEventListener('change', () => {}); 
  24.   document.getElementById('cpTagList101').addEventListener('click', () => {}); 
  25.   document.getElementById('gototop').addEventListener('click', () => {}); 
  26.   document.getElementById('asp10').addEventListener('click', () => {}); 
  27.  
  28. async function printEmployeeList() { 
  29.   const employees = await getEmployeeList(); 
  30.  
  31.   document.getElementById('employeeSelect').innerHTML = formatEmployeeList(employees); 
  32.  
  33. function formatEmployeeList(employees) { 
  34.   return employees.reduce( 
  35.     (content, employee) => content + employee.name + '<br>', 
  36.     '' 
  37.   ); 
  38.  
  39. function getEmployeeList() { 
  40.   return fetch('employeeList.json').then(res => res.json()); 

把逻辑提取到函数里

仔细看看startProgram函数的变化:

  • 首先,通过使用一个卫语句替换掉if-else语句。然后,启动数据库所需的逻辑提取到initDatabase函数中,并将事件侦听器添加到setListeners函数中。
  • 打印员工列表的逻辑稍微复杂一些,因此创建了三个函数:printEmployeeList, formatEmployeeList和getEmployeeList。
  • getEmployeeList负责向employeeList.json发出GET请求并以json格式返回响应。
  • 然后由printEmployeeList函数调用getEmployeeList,该函数获取员工列表并将其传递给formatEmployeeList函数,formatEmployeeList函数格式化并返回该列表。然后输出列表。

如你所见,每个功能只负责做一件事。

(编辑:晋中站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读