
* Modify rule S1479: allow statements with single-line clauses only * Improve compliant example * Improve description to match implementation * Address comments --------- Co-authored-by: Sebastien Marichal <sebastien.marichal@sonarsource.com>
89 lines
2.3 KiB
Plaintext
89 lines
2.3 KiB
Plaintext
== 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.
|
|
|
|
=== Exceptions
|
|
|
|
This rule ignores:
|
|
|
|
* `Select Case` statements over `Enum` arguments
|
|
* fall-through cases
|
|
* `Return` and `Throw` statements in `Case` clauses
|
|
|
|
== How to fix it
|
|
|
|
Extract the logic of multi-line `Case` clauses into separate methods.
|
|
|
|
=== Code examples
|
|
|
|
The examples below use the "Maximum number of case" property set to `4`.
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,vbnet,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,vbnet,diff-id=1,diff-type=compliant]
|
|
----
|
|
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
|
|
----
|
|
|
|
include::../resources-dotnet.adoc[]
|
|
|
|
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement[Select...Case Statement]
|
|
|
|
include::../rspecator-dotnet.adoc[]
|
|
|