DEV Community

🔥 pyronaur
🔥 pyronaur

Posted on • Edited on • Originally published at ndefine.com

Switches get stitches - a strategy for writing cleaner code.

Did you know that switches are the spawn of the devil put on earth to force developers into writing the some of the ugliest code on earth?

I'm kidding. They're only partially to blame.

In all seriousness, the switch statement is a really useful tool available in most of the modern programming languages. And for good reason - they're useful when you're in a pinch and still want to communicate clearly that based on your input value - multiple things can happen.

But there's a problem - with every update your code complexity is going to increase.

Switches get complicated, fast.

It may look like a nice clean switch today, until someone comes in and says, yeah, but on key 39, we want to also add a condition that if you haven't selected this text box - then move that other thing instead. And just like that, you've got a spaghetti noodle on your hands.

If your code is never going to be updated - go ahead, write switch statements, they're cool. But the chances are - your refactors will get refactors and as the application grows, so will your needs.

If not switches, then what?

🐻 I bear good news!

There's an easier way than using switches, and it may actually lead you to writing less code.

Here's a typical switch:

function getDirectionEmoji(direction) {
    let emoji;
    switch (direction) {
        case 'up':
            emoji = '👆';
            break;
        case 'down':
            emoji = '👇';
            break;
        case 'left':
            emoji = '👈';
            break;
        case 'right':
            emoji = '👉';
            break;
        default:
            emoji = '🧙‍♂️';
    }

    if( emoji === "🧙‍♂️") {
        console.log("You're a wizard, Harry.")
    }

    return emoji;
}

getDirectionEmoji('down');
// result: 👇
getDirectionEmoji('diagonally');
// result: 🧙‍♂️
Enter fullscreen mode Exit fullscreen mode

Even though there's nothing wrong with the code above, there's and easier way - a strategy pattern:

function getDirectionEmoji(direction) {
    const emojis = {
        'up': '👆',
        'down': '👇',
        'left': '👈',
        'right': '👉',
    };

    if( ! emojis[direction]) {
        console.log("You're a wizard, Harry.")
    }

    return emojis[direction] ?? '🧙‍♂️';
}

getDirectionEmoji('down');
// result: 👇
getDirectionEmoji('diagonally');
// result: 🧙‍♂️
Enter fullscreen mode Exit fullscreen mode

There are a number of benefits doing it this way:

1) By defining data first, it's easy for the reader to quickly predict what the rest of the code is going to do.

2) When complexity comes around, someone on your team isn't going to be tempted to just add one more thing inside that defined array and they'll have to create their own small island of code that deals with their specific edge case. Just remember to send them here if they add a switch statement.

I really like the strategy pattern for all things, both big and small - it helps you communicate clearly and encourages other good practices - like keeping your functions/methods simple and single purpose.

Top comments (0)