2016/10/01

How to easily avoid switch-case statement with function mapping in JavaScript

I won't advertise why it's good to avoid switch-case. While this matter might still be an open dispute I think there are usually better ways to implement what a switch-case does.

My vote would go for polymorphism, unfortunately much JavaScript code out there is not written following good OOP principles. So if you just need to work with given code base but not making a revolution there is a neat way to go:
const actions = {
    value1: actionX,
    value2: actionY,
    value3: actionZ
};

actions[value]();
Where action X, Y, Z are functions.

Of course it's good to add some check for undefined value, like:
actions[value] && actions[value]();

Or an error might be thrown if no mapping found as follows:
const action = actions[value]
        ? actions[value]
        : (value) => throw new Error('No action mapped for value: ' + value);

action(value);
Well, that's it. I believe it helps to reduce clutter in code. Just compare it to a typical switch:
switch (value) {
    case 'value1':
        actionX();
        break;
    case 'value2':
        actionY();
        break;
    case 'value3':
        actionZ();
        break;
    default: throw new Error('No action mapped for value: ' + value)
}


Exactly the same idea can be done in Groovy, Java and other languages if you are not up for polymorphism on a given case. Although for some languages with no functional paradigm, like Java before version 8, you may need to create some sort of Action class definition.

2 comments:

  1. Great survey, I'm sure you're getting a great response. Mason

    ReplyDelete


  2. Cleaning work is one of the most important areas that must be taken care of in order to maintain the safety of your furniture. Furniture is quickly exposed to dirt as a result of frequent use, in addition to children who have a major role in contaminating furniture and dirt, so we, as the best house cleaning company in Riyadh, rely on distinguished and modern tools.
    شركة تنظيف منازل بالباحة
    شركة تنظيف خزانات بالباحة

    Dear customers, we draw your attention to our use of effective and safe, healthy and environmentally friendly pesticides to spray the house, and we would like to inform you of our high-end goals, not just spraying, but also continuous follow-up to the customer with warranty.
    شركة مكافحة حشرات بالباحة

    ReplyDelete