加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

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

发布时间:2019-11-05 16:53:38 所属栏目:建站 来源:读芯术
导读:糟糕的代码可以运作,但迟早会让我们支付价钱。你有没有碰着过这样的题目:几周后,你无法领略本身的代码,于是不得不花上几个小时,乃至几天的时刻来弄清晰到底产生了什么。 办理这个常见题目的要领是使代码尽也许清楚。假如做得更好的话,纵然长短技强人

如你所见,这让人狐疑,也很难领略内里产生了什么。假若有错误呈现,都很难找到并修复它们。怎样改造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函数名目化并返回该列表。然后输出列表。

如你所见,每个成果只认真做一件事。

(编辑:湖南网)

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

热点阅读