当前位置: 首页 > 科技观察

避免过度使用IF语句的六个技巧

时间:2023-03-23 09:54:01 科技观察

最近,我在重构我以前的代码时,发现早期的代码使用了太多的if语句,达到了我从未见过的程度。这就是为什么我认为分享这些可以帮助我们避免使用过多if语句的简单技巧很重要。接下来,我将与大家分享这6个避免过度使用if的方法。这并不是要抵制使用if的偏执,而是换一种方式来思考我们的编程思想。1.三元条件运算符示例1:带有if的代码:functioncustomerValidation(customer){if(!customer.email){returnerror('emailisrequire')}elseif(!customer.login){returnerror('login是必需的')}elseif(!customer.name){returnerror('nameisrequired')}else{returncustomer}}重构代码:constcustomerValidation=customer=>!customer.email?错误(“需要电子邮件”):!customer.login?错误('需要登录'):!客户名称?error('nameisrequired'):customer示例2:代码withif:functiongetEventTarget(evt){if(!evt){evt=window.event;}如果(!evt){返回;}常量目标;如果(evt.target){target=evt.target;}else{target=evt.srcElement;returntarget;}重构代码:functiongetEventTarget(evt){evt=evt||窗口事件;returnevt&&(evt.target||代码为:constisOnline=true;constmakeReservation=()=>{};constuser={name:'Damian',age:32,dni:33295000};if(isOnline){makeReservation(user);}重构代码:constisOnline=true;constmakeReservation=()=>{};constuser={name:'Damian',age:32,dni:33295000};isOnline&&makeReservation(用户);示例2:带有if的代码:constactive=true;constloan={uuid:123456,ammount:10,requestedBy:'rick'};constsendMoney=()=>{};if(active&&loan){sendMoney();}重构代码:constactive=true;constloan={uuid:123456,ammount:10,requestedBy:'rick'};constsendMoney=()=>{};active&&loan&&sendMoney();3.函数委托示例1:带有if的代码:functionitemDropped(item,location){if(!item){returnfalse;}elseif(outOfBounds(location){varerror=outOfBounds;server.notify(item,error);items.resetAll();returnfalse;}else{animateCanvas();(item,location);returntrue;}}重构代码:functionitemDropped(item,location){constdropOut=function(){server.notify(item,outOfBounds);items.resetAll();返回假;}constdropIn=function(){server.notify(item,location);动画画布();返回真;}return!!item&&(outOfBounds(location)?dropOut():dropIn());}4.非分支策略示例1:带有开关的代码:switch(breed){case'border':return'BorderCollies是好男孩和好女孩。休息;case'pitbull':return'PitBullsaregoodboysandgirls.';休息;case'german':return'德国牧羊犬是好男孩和好女孩。休息;default:return'Imdefault'}重构代码:constdogSwitch=(breed)=>({"border":"BorderColliesaregoodboysandgirls.","pitbull":"PitBullsaregoodboysandgirls.","german":"德国牧羊犬是好男孩和好女孩。",})[breed]||'我是默认的';dogSwitch("borderxxx")5.作为我们在J中已知的数据的函数S中的函数是第一类,因此使用它我们可以将代码拆分为函数对象代码,如果:constcalc={run:function(op,n1,n2){constresult;if(op=="add"){结果=n1+n2;}elseif(op=="sub"){结果=n1-n2;}elseif(op=="mult"){结果=n1*n2;}elseif(op=="div"){结果=n1/n2;}返回结果;}}calc.run("sub",5,3);//2重构代码:constcalc={add:function(a,b){returna+b;},sub:function(a,b){返回a-b;},mult:function(a,b){返回a*b;},div:function(a,b){返回a/b;},运行:function(fn,a,b){returnfn&&fn(a,b);}}calc.run(calc.mult,7,4);//286.multMorphism多态性是一个对象具有多种形式的能力。OOP中多态性最常见的用法是使用父类引用来引用子类对象。带有if的代码:constbob={name:'Bob',salary:1000,job_type:'DEVELOPER'};constmary={name:'Mary',salary:1000,job_type:'QA'};constcalc=(person)=>{if(people.job_type==='DEVELOPER')returnperson.salary+9000*0.10;if(people.job_type==='QA')returnperson.salary+1000*0.60;}console.log('Salary',calc(bob));console.log('Salary',calc(mary));结构代码:constqaSalary=(base)=>base+9000*0.10;constdevSalary=(base)=>base+1000*0.60;//给对象添加函数.constbob={name:'Bob',salary:1000,job_type:'DEVELOPER',calc:devSalary};constmary={name:'Mary',salary:1000,job_type:'QA',calc:qaSalary};console.log('Salary',bob.calc(bob.salary));console.log('薪水',mary.calc(mary.salary));