如何寫更少的 if else

首先聲明,不是要消除if
而是,減小一些沒必要要的if判斷,使得代碼更優雅,更重要的是提升可維護性javascript

most easy

use Ternary:html

var result = condiction? trueResult : falseResult;

缺點:case 超過2個就不容易了java

use switch

in static type language

  • use heritance

usage (c++):c++

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

in Son classes6

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:web

//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 difficultjson

  • 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.ide

ref

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

相關文章
相關標籤/搜索