sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.18k stars 361 forks source link

Rule proposal: switch-case-limits #2439

Open lo1tuma opened 3 weeks ago

lo1tuma commented 3 weeks ago

Description

A rule that enforces the min or max amount of cases required per switch statement. E.g. a switch statement with just one case or two would be better expressed with if-else. At the same time a switch statement with too many cases might be better refactored to a lookup table.

{
  "switch-case-limits": [
    "error",
    { "min": 2, "max": 10 }
  ]
}

Fail

// min: 2
switch (foo) {
   case: 'bar':
      return 'BAR';
}
// max: 3
switch (foo) {
   case: 'bar1':
      return 'BAR1';
   case: 'bar2':
      return 'BAR2';
   case: 'bar3':
      return 'BAR3';
   case: 'bar4':
      return 'BAR4';
}

Pass

// min: 2
switch (foo) {
   case: 'bar1':
      return 'BAR1';
  case: 'bar2':
      return 'BAR2';
}
// max: 3
switch (foo) {
   case: 'bar1':
      return 'BAR1';
   case: 'bar2':
      return 'BAR2';
   case: 'bar3':
      return 'BAR3';
}

Proposed rule name

switch-case-limits

Additional Info

No response

fregante commented 3 weeks ago

I agree that switches with one case unnecessarily verbose, I don't think a large number of cases is inherently bad though.

If they're a list of 15 case/return lines line in your example I think it's fine. Many cases are usually unreadable when each case has 30+ lines each. At that point the native complexity or max-lines-per-function might just do it.

sindresorhus commented 2 weeks ago

I also don't really see the problem with large switches. I do think the first example with the single case could be its own rule though.

zanminkian commented 1 week ago

You can use the rule no-small-switch and max-switch-cases in eslint-plugin-sonarjs. IMO, no need to implement it here.

lo1tuma commented 1 week ago

You can use the rule no-small-switch and max-switch-cases in eslint-plugin-sonarjs. IMO, no need to implement it here.

I’m using eslint-plugin-sonarjs v1, but they recently released v2 which brings in tons of framework-specific rules with additional dependencies that I don’t need or want. That’s why I’m looking for alternatives and I though eslint-plugin-unicorn could be a good fit.


At that point the native complexity or max-lines-per-function might just do it.

That’s a good point, the complexity rule should detect large switches.


I do think the first example with the single case could be its own rule though.

Should it be still configurable what the threshold of cases should be or just hardcoded to one (e.g. no-single-case-switch). Personally I would also say for two cases a simple if/else would be better.