2021-01-27 13:42:22 +01:00
When ``++switch++`` statements have large sets of case clauses, it is usually an attempt to map two sets of data. A ``++Dictionary++`` should be used instead to make the code more readable and maintainable.
2020-06-30 12:47:33 +02:00
== Noncompliant Code Example
With a "Maximum number of case" set to 4
2020-06-30 14:49:38 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
public class TooManyCase
{
public int switchCase(char ch)
{
switch(ch) { // Noncompliant
case 'a':
return 1;
case 'b':
case 'c':
return 2;
case 'd':
return 3;
case 'e':
return 4;
case 'f':
case 'g':
case 'h':
return 5;
default:
return 6;
}
}
}
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
using System.Collections.Generic;
public class TooManyCase
{
Dictionary<char, int> matching = new Dictionary<char, int>()
{
{'a', 1}, {'b', 2}, {'c', 2}, {'d', 3},
{'e', 4}, {'f', 5}, {'g', 5}, {'h', 5}
};
public int withDictionary(char ch)
{
int value;
if (this.matching.TryGetValue(ch, out value)) {
return value;
} else {
return 6;
}
}
}
----
== Exceptions
2021-01-27 13:42:22 +01:00
This rule ignores ``++switch++``es over ``++Enum++``s and empty, fall-through cases.
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::../parameters.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]