Switches get stitches - a strategy for writing cleaner code.

pyronaur

šŸ”„ pyronaur

Posted on January 25, 2022

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.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
pyronaur
šŸ”„ pyronaur

Posted on January 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related