码迷,mamicode.com
首页 > 其他好文 > 详细

如何写更少的 if else

时间:2018-08-20 22:59:59      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:dde   asc   val   ret   extend   可维护性   html   mis   sage   

首先声明,不是要消除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

如何写更少的 if else

标签:dde   asc   val   ret   extend   可维护性   html   mis   sage   

原文地址:https://www.cnblogs.com/no7dw/p/9508294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!