Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explicitly specify 2 separate cases that fall through #372

Closed
mgmacias95 opened this issue Apr 16, 2019 · 0 comments
Closed

Explicitly specify 2 separate cases that fall through #372

mgmacias95 opened this issue Apr 16, 2019 · 0 comments
Assignees
Labels

Comments

@mgmacias95
Copy link
Contributor

The comma operator (,) evaluates its operands, from left to right, and returns the second one. That's useful in some situations, but just wrong in a switch case. You may think you're compactly handling multiple values in the case, but only the last one in the comma-list will ever be handled. The rest will fall through to the default.

Similarly, the logical OR operator (||) will not work in a switch case, only the first argument will be considered at execution time.

Noncompliant Code Example

switch a {
  case 1,2:  // Noncompliant; only 2 is ever handled by this case
    doTheThing(a);
  case 3 || 4: // Noncompliant; only '3' is handled
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log("Neener, neener!");  // this happens when a==1 or a == 4
}

Compliant Solution

switch a {
  case 1:
  case 2:
    doTheThing(a);
  case 3:
  case 4:
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log("Neener, neener!");
}

switch (config.logs) {
case "INFO", "info":
logger_level = LEVEL_INFO;
break;
case "WARNING", "warning":
logger_level = LEVEL_WARNING;
break;
case "ERROR", "error":
logger_level = LEVEL_ERROR;
break;
case "DEBUG", "debug":
logger_level = LEVEL_DEBUG;
break;
case "DISABLED", "disabled":
logger_level = LEVEL_DISABLED;
break;
default:
logger_level = LEVEL_INFO;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants