DEV Community

Discussion on: JS Refactoring Combo: Replace Nested If-Else with Guards

 
rkallan profile image
RRKallan

if we look to the original code then my assumption isDead, isSeparated & isRetired are booleans.

So in the solution provided as object result needs to be set.

a possible solution could be

function getPayAmount() {
    const cases = {
        deadAmount,
        separatedAmount,
        retiredAmount,
        normalPayAmount,
    };
    let result = "normalPay";

    if (isDead) result = "dead";
    if (isSeparated) result = "separated";
    if (isRetired) result = "retired";

    return cases[`${result}Amount`]();
}

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
lgrammel profile image
Lars Grammel • Edited

Agreed. Overall this goes back to my point that an object lookup is not the best refactoring here, since there is a risk that it'll change behavior and introduce bugs. Plus it adds unnecessary cognitive complexity.

Btw, I'm a huge fan of using the object lookup pattern when there is a need for it, e.g. when there are many entries or when the entries need to be assembled. In this example tho I think simple if statements are way easier to understand.

Thread Thread
 
rkallan profile image
RRKallan

Agree that if statements with return is easier in this case