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.
时间: 2024-10-12 18:58:58