首页 > 编程语言 > 详细

[Javascript] Refactoring: Polymorphic Functions

时间:2016-04-24 06:06:35      阅读:275      评论:0      收藏:0      [点我收藏+]

if-statements can add serious complexity and beg for refactoring. You can use polymorphic functions to simplify your ifs and dynamically call the appropriate method.

 

For example you have the code like:

function charge(){

    if(this.moive.type==="regular"){
        // ...some logic
        if(this.daysRented > 2){
            // ...some logic
        }
    }else if(this.moive.type==="new release"){
        // ...some logic
    }else if(this.moive.type==="childrens"){
        // ...some logic
        if(this.daysRented > 3){
            // ...some logic
        }    
    }
    
    return amount;
}

 

We can refactor to:

require("activesupport")

this.charge = () => {
    return this.[this.type.titleize().split(" ").join(‘‘).camelize() + "Charge"](daysRented);
}

this.regularCharge = ()=>{
    if(daysRented > 2){
    
    }
} 

this.newRelseaseCharge = () => {

}

this.childrenCharge = () => {
    if(daysRented > 3){
    
    }
}

So based on the type we will call different function.

[Javascript] Refactoring: Polymorphic Functions

原文:http://www.cnblogs.com/Answer1215/p/5426188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!