When Select Case statements
have large sets of multi-line Case clauses, the code becomes hard to read and maintain.
For example, the 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.
This rule ignores:
Select Case statements over Enum arguments Return and Throw statements in Case clauses Extract the logic of multi-line Case clauses into separate methods.
The examples below use the "Maximum number of case" property set to 4.
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
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