码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Refactoring: Polymorphic Functions

时间:2016-04-24 06:07:13      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!