samedi 15 août 2020

Should a switch / if-elseif-else function have a default case which returns null if no case matched and handled in the handler?

Case 1 (throws error is no switch case matched):

function getColorName(c) {
  switch(c) {
      case Color.Red:
          return 'red, red wine';
      case Color.Green:
          return 'greenday';
      case Color.Blue:
          return "Im blue, daba dee daba";
      default:
          throw new Error('error');
  }
}

getColorName(Color.Yellow); // this results in an error thrown

Case 2 (the default case returns null and that's handled in the caller):

function getColorName(c) {
  switch(c) {
      case Color.Red:
          return 'red, red wine';
      case Color.Green:
          return 'greenday';
      case Color.Blue:
          return "Im blue, daba dee daba";
      default:
          return null;
  }
}

if (getColorName(Color.Yellow)) {
  // do stuff here 
}

This might not be the perfect example. However, the goal of the question is to understand what is the approach which covers as many use cases as possible while avoiding excessive complexity when a switch logic exist?

While out of the scope of the question, as a means of clarification of possible use cases, the switch would be implemented either

  1. with a switch (like above)
  2. as a if-elseif-else function (if the switch cases are complex or there are only few cases)

if-elseif-else example (for reference):

function getColorName(c) {
    if (Color.Red) { 
       return 'red, red wine';
    }
    else if (Color.Green) {
       //... 
    }
    // etc. (--cut--)
    else {
       return null;
    }
}

Aucun commentaire:

Enregistrer un commentaire