Skip to main content

Use object instead of huge switch

Medium
Clean codeTypescriptJavaScriptK.I.S.S

What do do

  • Limit to 5 cases
  • Use an array or a dictionnary to access
  • Factorisation of case

Prevent problems

  • Readibility
  • Bad evolution
  • Difficult tests
  • Performance

Explanation

The switch is easy to understand, but it's not performant. We have to have one line per case, and if we have a lot of case, we can read in one page all case.

Examples

Example 1:

Negative

Incorrect implementation that violates the practice.

function weekday1(day) {
switch (day) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
throw new Error("day must be in range 1 to 7");
}
}