设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

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

发布时间:2019-11-05 10:05 所属栏目:21 来源:读芯术
导读:如你所见,这让人困惑,也很难理解里面发生了什么。如果有错误出现,都很难找到并修复它们。如何改进startProgram函数?可以将公共逻辑提取到函数中。以下是具体操作方法: functionstartProgram(){ if(!window.inde

如你所见,这让人困惑,也很难理解里面发生了什么。如果有错误出现,都很难找到并修复它们。如何改进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函数格式化并返回该列表。然后输出列表。

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

我们仍然可以对函数进行一些修改,其实,应用程序很需要把视图从控制器中分离出来,但总体而言,startprogram函数现在信息很容易懂,理解它的功能绝对没有困难。如果几个月后必须重新用这段代码,那也不是什么难事。

小结

程序员是唯一负责编写高质量代码的人。我们都应该养成从第一行就写好代码的习惯。编写清晰易懂的代码并不难,这样做对你和你的同事都有好处。

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读