rspec/rules/S1479/vbnet/rule.adoc

75 lines
2.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2023-06-15 16:30:42 +02:00
When https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement[Select Case] statements have large sets of case clauses, it is usually an attempt to map two sets of data. A https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2[Dictionary] should be used instead to make the code more readable and maintainable.
2020-06-30 12:47:33 +02:00
2023-06-15 16:30:42 +02:00
=== Exceptions
This rule ignores `Select Case` statements over `Enum` arguments and empty, fall-through cases.
== How to fix it
Store all the cases apart from the `Case Else` one in a dictionary and try to get the matching value by calling the https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue[TryGetValue] method.
2020-06-30 12:47:33 +02:00
2023-06-15 16:30:42 +02:00
=== Code examples
2023-06-15 16:30:42 +02:00
==== Noncompliant code example
[source,vbnet,diff-id=1,diff-type=noncompliant]
2020-06-30 12:47:33 +02:00
----
Public Class TooManyCase
2023-06-15 16:30:42 +02:00
Public Function MapValues(Ch As Char) As Integer
Select Case Ch ' Noncompliant: 5 cases, "Case Else" excluded, more than maximum = 4
2020-06-30 12:47:33 +02:00
Case "a"c
Return 1
Case "b"c, "c"c
Return 2
Case "d"c
Return 3
Case "e"c
Return 4
Case "f"c, "g"c, "h"c
Return 5
Case Else
Return 6
End Select
End Function
End Class
----
2023-06-15 16:30:42 +02:00
==== Compliant solution
2020-06-30 12:47:33 +02:00
2023-06-15 16:30:42 +02:00
[source,vbnet,diff-id=1,diff-type=compliant]
2020-06-30 12:47:33 +02:00
----
Public Class TooManyCase
Private fMatching As New Dictionary(Of Char, Integer) From {
2023-06-15 16:30:42 +02:00
{ "a"c, 1 },
{ "b"c, 2 },
{ "c"c, 2 },
{ "d"c, 3 },
{ "e"c, 4 },
{ "f"c, 5 },
{ "g"c, 5 },
{ "h"c, 5 },
2020-06-30 12:47:33 +02:00
}
2023-06-15 16:30:42 +02:00
Public Function MapValues(Ch As Char) As Integer
2020-06-30 12:47:33 +02:00
Dim Value As Integer
If fMatching.TryGetValue(Ch, Value) Then
Return Value
Else
Return 6
End If
End Function
End Class
----
2023-06-15 16:30:42 +02:00
include::../resources-dotnet.adoc[]
* https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement[Select...Case Statement]
2023-06-15 16:30:42 +02:00
include::../rspecator-dotnet.adoc[]