DEV Community

loading...

Discussion on: If (all) else is complicated, switch to switch?

Collapse
ohryan profile image
Ryan

TBH I've never considered doing this but now that I see it, it feels like an abuse of the switch statement.

Neither example seems particularly "clean" to me.

My preference would be to refactor this code such that you can return early.

function getLogMessage() {
    if (someExpressionA) {
        return 'yes';
    }

    if (someExpressionB && someExpressionC || someExpressionD) {
        return 'nope';
    }

    return 'maybe';
}

console.log(getLogMessage())
Enter fullscreen mode Exit fullscreen mode

Much more straightforward than either IMHO.

Collapse
jmdejager profile image
🐤🥇 Jasper de Jager Author

I agree, the console.log was purely for the example. I also think most people will agree with you, my first feeling was also that it feels hacky. But... There are people that do use it, so it is good to know it exists 🙂

Collapse
branzz profile image
Branzz

Which can, in turn, be simplified by Java 13's Enhanced Switch statement (or even a ternary statement at that point).

console.log(switch(true) {
    case someExpressionA -> "yes";
    case someExpressionB && someExpressionC || someExpressionD -> "nope";
    default -> "maybe";
});
Enter fullscreen mode Exit fullscreen mode
Collapse
jmdejager profile image
🐤🥇 Jasper de Jager Author

Thnx for sharing! Honored to be your first comment 😊😉

Forem Open with the Forem app