[Javascript] Refactoring: Polymorphic Functions

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.

原文地址:https://www.cnblogs.com/Answer1215/p/5426188.html