lundi 4 janvier 2016

Better approach for processing values: Switch VS If

I have a condition in my code where I have sets of value which have same handling. Now I have implemented it using switch, but have used fallthrough init.

JSFiddle Link.

Sample Code

function validateSwitch() {
  var value = document.getElementById("txt").value;
  switch (value) {
    case "a":
    case "b":
    case "c":
      console.log("Foo");
      break;
    case "d":
    case "e":
    case "f":
      console.log("Bar");
      break;
    default:
      console.log("Default");
      break;
  }
}

function validateIf() {
  var value = document.getElementById("txt").value;
  if (value === 'a' || value === 'b' || value === 'c') {
    console.log("Foo");
  } else if (value === 'd' || value === 'e' || value === 'f') {
    console.log("Foo");
  } else {
    console.log("Default");
  }
}
<input type="text" id="txt">
<button onclick="validateSwitch()">Switch</button>
<button onclick="validateIf()">If</button>

In above code, there are 2 approaches, validateSwitch and validateIf. Question is, which one is a better approach/ideal. Does fallthrough impacts readability of the code?

Note: This is just a sample with dummy values. Actual values are different.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire