Change S1301 or make parameterizable

Rule S1301 (various languages) says not to use a switch if there are only 1 or 2 cases, use an if-else instead.

While I agree with 1 case, I don’t know about 2 cases. If the condition being switched on is more than just a simple variable with a short name, then it’s more work for the reader to see that the expressions in the if and elseif conditions are the same thing. And if the condition is complex or involves a function call and you address that by evaluating it once and assigning it to a temp variable, that’s just another chain that has to be followed by the reader.

I would claim that

switch (foo.bar.someReallyLongMemberName) {
case 1: …
case 2: …
default: …
}

is more readable than

if (foo.bar.someReallyLongMemberName == 1) { …
} elseif (foo.bar.someReallyLongMemberName == 2) { …
} else { …
}

or

fbSrlmn = foo.bar.someReallyLongMemberName;
if (fbSrlmn == 1) { …

So I would suggest one of:

  1. Making the limit a user-settable parameter (default 3);
  2. If (1) is too hard, make a simple binary switch to select a limit of either 3 (default) or 2;
  3. Or just change the threshold to 2.