rspec/rules/S1479/vbnet/rule.adoc

89 lines
2.3 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
When https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement[Select Case] statements have large sets of multi-line `Case` clauses, the code becomes hard to read and maintain.
For example, the https://www.sonarsource.com/docs/CognitiveComplexity.pdf[Cognitive Complexity] is going to be particularly high.
In such scenarios, it's better to refactor the `Select Case` to only have single-line case clauses.
When all the `Case` clauses of a `Select Case` statement are single-line, the readability of the code is not affected.
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
* fall-through cases
* `Return` and `Throw` statements in `Case` clauses
2023-06-15 16:30:42 +02:00
== How to fix it
Extract the logic of multi-line `Case` clauses into separate methods.
2020-06-30 12:47:33 +02:00
2023-06-15 16:30:42 +02:00
=== Code examples
The examples below use the "Maximum number of case" property set to `4`.
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 Function MapChar(ch As Char, value As Integer) As Integer ' Noncompliant
Select Case ch
Case "a"c
Return 1
Case "b"c
Return 2
Case "c"c
Return 3
' ...
Case "-"c
If value > 10 Then
Return 42
ElseIf value < 5 AndAlso value > 1 Then
Return 21
End If
Return 99
Case Else
Return 1000
End Select
End Function
2020-06-30 12:47:33 +02:00
----
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 Function MapChar(ch As Char, value As Integer) As Integer
Select Case ch
Case "a"c
Return 1
Case "b"c
Return 2
Case "c"c
Return 3
' ...
Case "-"c
Return HandleDash(value)
Case Else
Return 1000
End Select
End Function
Private Function HandleDash(value As Integer) As Integer
If value > 10 Then
Return 42
ElseIf value < 5 AndAlso value > 1 Then
Return 21
End If
Return 99
End Function
2020-06-30 12:47:33 +02:00
----
2023-06-15 16:30:42 +02:00
include::../resources-dotnet.adoc[]
* Microsoft Learn - 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[]