Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice for a case to have multiple breaks?

This is a super dumbed down version of what I am doing, but imagine needing to perform multiple validations on an object within a switch statement. At any point in the validation we may decide that we do not want to continue working with the object.

The dumb example:

var yummies = [
  {name: 'apples', quantity: 3},
  {name: 'apples', quantity: 4}
];

var purchases = [];

for (var i = 0; i < yummies.length; i++) {
  var yummy = yummies[i];
  switch (yummy.name) {
      case 'apples':
        if (purchases.indexOf(yummy.name) > -1) {
          break;
        }

        //A ton of other code including, possibly other breaks

        purchases.push(yummy.name);
        break;
  }
}

A return won't work as I still want to continue through the loop. I think I could go with a continue statement could work, but it looks really off seeing a continue in a switch/case.

Anyways, two breaks in a single case. Any reason not to do it?

like image 326
KJ Price Avatar asked Sep 25 '15 21:09

KJ Price


Video Answer


1 Answers

This of course is just an opinion, but I don't think it's bad per se. However, nested cases, ifs and other control structures don't make your code very readable. In situations like this, you might consider moving pieces of code to separate functions.

So your code could look like this:

function purchaseApple(yummyName) {
  if (purchases.indexOf(yummyName) == -1) {
    purchases.push(yummyName);
  }
}

for (var i = 0; i < yummies.length; i++) {
  var yummy = yummies[i];
  switch (yummy.name) {
      case 'apples':
        purchaseApples(yummy.name);
        break;
  }
}

Or maybe even move the condition to the function too:

function tryPurchaseApple(yummyName) {
  if (yummyName == 'apples' && purchases.indexOf(yummyName) == -1) {
    purchases.push(yummyName);
  }
}

for (var i = 0; i < yummies.length; i++) {
  var yummy = yummies[i];
  tryPurchaseApple(yummy.name);
  tryPurchasePears(yummy.name);
}

These are just suggestions, of course. It's hard to make a sensible example out of this situation, no offence. ;)

like image 64
GolezTrol Avatar answered Sep 29 '22 07:09

GolezTrol