Switch is EVIL! (Part 2)

In the last post we talked about evolution of languages and how switch got stuck in OO languages, causing code to be modified, leading to bugs and more regression testing.

It the first part we saw how “value-replacement” switch-cases can easily be converted into arrays but what if we don’t have contiguous range (1 – 7 weekdays, 1 – 12 month names). Let’s consider scenario where we have non-contiguous values for “value-replacement”.

// Get key label for given key code of keyboard
function keyLabel(keyCode) {
switch (keyCode) {
case 33:
name = "{PGUP}";
break;
case 45:
name = "{INS}";
break;
case 121:
name = "{F10}"
}
return name;
}

Unfortunately, we cannot use an array for this as we would have to create a sufficiently large array which will have most elements blank (undefined). That would not only be wasteful but would require extra checks whether the value is missing at a given element or not.

Maps to the rescue
// Convert switch-case to a "lookup map"
function keyName(keyCode) {
// Create a "map" (object in JavaScript)
const keyMap = {
33: "{PGUP}",
45: "{INS}",
121: "{F10}"
};
// Now look up keyCode in map
return keyMap[keyCode];
}
view raw LookupMap.js hosted with ❤ by GitHub

But what if the values can change dynamically? Maybe we want to change the keymap before we run this application next time? Or maybe we want to add new keys to the keymap while the program is running?

Dynamically load the keymap from JSON file (keymap.json)
{
    "33": "{PGUP}",
    "45": "{INS}",
    "121": "{F10}"
}
Update code to use external maps
// Convert switch-case to
// dynamically loadable map
function keyName(keyCode) {
// Load the keymap from a file
const keyMap = require("./keymap.json");
// Now look up keyCode in map
return keyMap[keyCode];
}

Wonderful! Now we have made this code maintainable by eliminating the switch-case and loading keyCode and keyName from an external source like JSON file. It could very well be an AJAX call or retrieval from a database.

Stay tuned for more Switchzilla (Switch Killer) 👍

Switch is EVIL Series

  1. Switch is EVIL! (Part 1) – Convert it to arrays
  2. Switch is EVIL! (Part 2) – Convert it to maps
  3. Switch is EVIL! (Part 3) – Create function maps
  4. Switch is EVIL! (Part 3a) – Implementing in Java
  5. Switch is EVIL! (Part 3b) – Implementing in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s