如何写更少的 if else

首先声明,不是要消除if
而是,减少一些不必要的if判断,使得代码更优雅,更重要的是提高可维护性

most easy

use Ternary:

var result = condiction? trueResult : falseResult;  

缺点:case 超过2个就不容易了

use switch

in static type language

  • use heritance

usage (c++):

  SonClasss son = new FatherClass()
  son.doSomething()

in Son class

  protected void doSomething(){
    //here override the FatherClass implement
    print("I did something different from my father");
  }
  • use polypeptide

in dynamic type language

also: you can use heritance way in class:

  //es5
  function Son(){};
  util.inherits(Son, Father);
  Son.prototype.doSomething(){
    console.log("I did something different from my father");
  }
  //usage:
  var son = new Son();
  son.doSomething();
  //es6 use extends
  //

in dynamic lange, your choice become something different and sometimes difficult

  • use array
  //usage:
  //req.query = {"name":"Wade", "surname": "Deng"}
  SonClass son = new ClassFactory(req.query.name);
  son.doSomething();
  
  //ClassFactory implement   , if else hidden in ClassFactory
  function ClassFactory(name){
    this.name = name;
    this.subClass = name == "Wade" ? new subClass(name)  : new sub2Class(name);
  }
  
  • use key-value json
SonClass.prototype.doSomething(actionName){
  var do = {
    'cry' :{ console.log('cry');}
    'eat' :{ console.log('eat');}
  }
  return do(actionName);
}

However , sometime reading a few if else statements is easy.

ref

[anti-if-else-patterns](http://www.techug.com/anti-if-the-missing-patterns
no more ifs alternatives
anti-anti-if

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值