[Javascript] Refactoring: Polymorphic Functions

时间:2023-03-08 22:43:30

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 > ){
// ...some logic
}
}else if(this.moive.type==="new release"){
// ...some logic
}else if(this.moive.type==="childrens"){
// ...some logic
if(this.daysRented > ){
// ...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 > ){ }
} this.newRelseaseCharge = () => { } this.childrenCharge = () => {
if(daysRented > ){ }
}

So based on the type we will call different function.