
org.sonar.plugins.vbnet.S1479.html Maven / Gradle / Ivy
Why is this an issue?
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.
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
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
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
Resources
Documentation
- Sonar - Cognitive Complexity
- Microsoft Learn - Select…Case Statement
© 2015 - 2025 Weber Informatics LLC | Privacy Policy