首页 > 编程语言 >编程技巧

编程技巧

时间:2023-05-09 11:14:57浏览次数:35  
标签:execute 菜单 console 技巧 编程 log obj name

一 接口和面向接口编程

1 用ts编写基于 interface 的命令模式

编写用户界面程序,页面有成百上千个子菜单

约定基于命令模式编写

  • 负责子菜单的同事 完成编程之后会将子菜单封装成一个命令对象,将其交给编写菜单集合界面的同事

约定:调用子菜单的 execute 方法时会执行对应子菜单的命令

class RefreshMenuBarCommand {
  execute() {
    console.log('刷新菜单界面');
  }
}
class AddSubMenuCommand {
  execute() {
    console.log('增加子菜单');
  }
}
class DelSubMenuCommand {
  execute() {
    console.log('删除菜单界面');
  }
}
let refreshMenuBarCommand = new RefreshMenuBarCommand()
let addSubMenuCommand = new AddSubMenuCommand()
let delSubMenuCommand = new DelSubMenuCommand()

let setCommand = command => {
  document.getElementById('execCommand').onclick = () => commond.execute()
}
setCommand(refreshMenuBarCommand)
setCommand(addSubMenuCommand)
setCommand(delSubMenuCommand)
防止某个子命令对象没有实现 execute 方法,在高层函数中添加一段防御性代码
let setCommand = command => {
  document.getElementById('execCommand').onclick = () => {
    if(typeof command.execute !== 'function') {
      throw new Error('command对象必须实现execute方法')
    }
    commond.execute()
  }
}

2 ts版本的命令模式

1. 定义 Command 接口
interface Command {
    execute: Function;
}
2. 定义类
class RefreshMenuBarCommand implements Command {
    constructor() {}
    execute() {
        console.log('刷新菜单界面');
    }
}
class AddSubMenuCommand implements Command {
    constructor() {}
    execute() {
        console.log('增加子菜单');
    }
}
class DelSubMenuCommand implements Command {
    constructor() {}
    execute() {
        console.log('删除菜单界面');
    }
}

二 代码重构

1 提炼函数

  • 避免出现超大函数
  • 独立出来的函数
    • 有助于代码复用
    • 更容易被覆写
    • 如果拥有一个良好的命名,它本身就起到了注释的作用

2 合并重复的条件片段

function paging(currPage) {
 if(currPage <= 0) {
    currPage = 0;
    jump(currPage);
  } else if(currPage >= totalPage) {
    currPage = totalPage;
    jump(currPage);
  } else {
    jump(currPage);
  }
}

独立重复代码

function paging(currPage) {
  if(currPage <= 0) {
    currPage = 0;
  } else if(currPage >= totalPage) {
    currPage = totalPage;
  } 
  jump(currPage);
}

3 把条件分支语句提炼成函数

规则:夏季全部商品打八折出售

function getPrice(price) {
  let date = new Date();
  if(date.getMonth() >= 6 && date.getMonth() <= 9) {
    return price * 0.8;
  }
  return price;
}

提炼条件分支语句

更准确地表达代码的意思,函数名本身又能起到注释的作用

function isSsummer() {
  let date = new Date();
  return date.getMonth() >= 6 && date.getMonth() <= 9;
}
function getPrice(price) {
  if(isSummer()) {
    return price * 0.8;
  }
  return price;
}

4 合理使用循环

5 提前让函数退出代替嵌套条件分支

函数只有一个出口

function del(obj) {
  let ret;
  if(!obj.isReadOnly) {
    if(obj.isFolder) {
      ret = deleteFolder(obj);
    } else if(obj.isFile) {
      ret = deleteFile(obj);
    }
  }
  return ret;
}

翻转外层if判断

function del(obj) {
  let ret;
  if(obj.isReadOnly) {
    return;
  }
  if(obj.isFolder) {
    ret = deleteFolder(obj); 
  } else if(obj.isFile) {
    ret = deleteFile(obj);
  }
  return ret;
}

6 传递对象参数代替过长的参数列表

7 尽量减少参数数量

8 少用三目运算符

9 合理使用链式调用

让方法调用结束后返回对象自身

class User {
  constructor() {
    this.id = null;
    this.name = null;
  }
  setId(id) {
    this.id = id;
    return this;
  }
  setName(name) {
    this.name = name;
    return this;
  }
}
console.log(
  new User().setId(12).setName('lisi')
);
  • 若其中一步出错,增加调试难度
  • 若链条容易发生改变,导致调试和维护困难

10 分解大型类

街头霸王

class Spirit {
  constructor(name) {
    this.name = name;
  }
  attack(type) {
    if(type === 'waveBoxing') {
      console.log(this.name + ': 使用波动拳');
    } else if(type === 'whirlKick') {
      console.log(this.name + ': 使用旋风腿');
    }
  }
}
  • attack 方法过于庞大 -> 有必要作为一个单独的类
class Attack {
  constructor(spirit) {
    this.spirit = spirit;
    this.list = {};
    this.init()
  }
  start(type) {
    return this.list[type].call(this)
  }
  init() {
    this.list = {
      waveBoxing() {
        console.log(this.spirit.name + ': 使用波动拳');
      },
      whirlKick() {
        console.log(this.spirit.name + ': 使用旋风腿');
      }
    }
  }
}
class Spirit {
  constructor(name) {
    this.name = name;
    this.attackObj = new Attack(this);
  }
  attack(type) {
    this.attackObj.start(type);
  }
}

11 return 退出多重循环

  • break -> return
  • 把循环后面的代码放到return后面
    • 代码多 -> 提炼成函数

标签:execute,菜单,console,技巧,编程,log,obj,name
From: https://www.cnblogs.com/pleaseAnswer/p/17384227.html

相关文章

  • 免费享用ChatGPT4.0小技巧,构思方式新颖巧妙,可借鉴,独家分享
    文/高扬(微信公众号:量子论) 现在大家免费使用的ChatGPT都是GPT-3.5版本,可是我就想使用GPT-4版本怎么办,而且我还不想购买OpenAI的Plus会员…… 我是这样考虑的,作为大语言模型,我们并不知道GPT-3.5和GPT-4是不是同一个模型。 不如我们先猜测它们归属同一种模型,只是OpenAI的......
  • 不同设备如何统一语言编程平台高效开发?本文为你揭秘
     原文:https://mp.weixin.qq.com/s/8UHznZenc7A_UICta2bETg,点击链接查看更多技术内容。 随着数字化时代的发展,手机、平板、PC、电视、智能手表、车机等智能设备的普及率越来越高,但不同设备往往搭载了不同的操作系统。面对不同的操作系统与开发框架,应用开发难度大、成本高;同......
  • python 小技巧, 列表生成式比 filter(lambda x:x>=0,data) 快, iteritems()方法,
    题目经timeit测试列表生成式比filter(lambdax:x>=0,data)快python2的dict的iteritems()方法,pyhton3可以看看有没有......
  • 对比编程语言的四种错误处理方法,哪种才是最优方案?
    作者:AndreaBergia译者:豌豆花下猫@Python猫英文:Errorhandlingpatterns转载请保留作者及译者信息!错误处理是编程的一个基本要素。除非你写的是“helloworld”,否则就必须处理代码中的错误。在本文中,我将讨论各种编程语言在处理错误时使用的最常见的四种方法,并分析它们的优......
  • 第七届河南省赛 zzuoj 10403: D.山区修路 (DP转换&&技巧)
    10403:D.山区修路TimeLimit: 2Sec  MemoryLimit: 128MBSubmit: 68  Solved: 22[Submit][Status][WebBoard]Description某山区的孩子们上学必须经过一条凹凸不平的土路,每当下雨天,孩子们非常艰难。现在村里走出来的Dr.Kong决定募捐资金重新修建着条路......
  • LightOJ - 1058 Parallelogram Counting (数学几何&技巧)给n个点求组成平行四边形个数
    LightOJ-1058ParallelogramCountingTimeLimit: 2000MSMemoryLimit: 32768KB64bitIOFormat: %lld&%lluSubmit StatusDescriptionThereare n distinctpointsintheplane,givenbytheirintegercoordinates.Findthenumberofparallelogramswhosever......
  • CodeForces - 621B Wet Shark and Bishops (数学几何&技巧)
    TimeLimit: 2000MS MemoryLimit: 262144KB 64bitIOFormat: %I64d&%I64uCodeForces-621BWetSharkandBishopsSubmit StatusDescriptionToday,WetSharkisgiven n bishopsona 1000 by 1000 grid.Bothrowsandcolumnsofthegridarenumberedfro......
  • 编程打卡: C++ 语言程序设计
    编程打卡:C++语言程序设计#include<iostream>#include<array>usingnamespacestd;intmain(){intn;cin>>n;array<double,100000>scores;for(inti=0;i<n;i++){cin>>scores[i];}......
  • 2023.5.8编程一小时打卡
    一、问题描述:初始化int类型数组date1[]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20},应用本章的直接插入排序模板进行排序,对此函数模板稍作修改,加入输出语句,在每一个待排序元素后显示整个数组,观察排序过程中数据的变化,加深对插入排序算法的理解。二、解题思路:首先,定......
  • 在网络编程中涉及中文的编码解码的问题
    在网络编程中涉及中文需要编码解码的场景编码URLEncoder.encode("我最爱桃子了","utf-8")解码URLdecoder.decode("我最爱桃子了","utf-8");......