S3385: Remove Exit For, Do, While and Try (#4654)

This commit is contained in:
Pavel Mikula 2025-02-10 08:39:26 +01:00 committed by GitHub
parent d9e29030ae
commit 6ef35e2a8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,15 +1,8 @@
== Why is this an issue? == Why is this an issue?
Other than ``++Exit Select++``, using an ``++Exit++`` statement is never a good idea. `Exit Function`, `Exit Property`, and `Exit Sub` are all poor, less-readable substitutes for a simple `Return`, and if used with code that should return a value (`Exit Function` and in some cases `Exit Property`) they could result in a `NullReferenceException`.
This rule raises an issue for all their usages.
``++Exit Do++``, ``++Exit For++``, ``++Exit Try++``, and ``++Exit While++`` will all result in unstructured control flow, i.e. spaghetti code.
``++Exit Function++``, ``++Exit Property++``, and ``++Exit Sub++`` are all poor, less-readable substitutes for a simple ``++return++``, and if used with code that should return a value (``++Exit Function++`` and in some cases ``++Exit Property++``) they could result in a ``++NullReferenceException++``.
This rule raises an issue for all uses of ``++Exit++`` except ``++Exit Select++`` and ``++Exit Do++`` statements in loops without condition.
=== Noncompliant code example === Noncompliant code example
@ -17,25 +10,20 @@ This rule raises an issue for all uses of ``++Exit++`` except ``++Exit Select++
[source,vbnet] [source,vbnet]
---- ----
Public Class Sample Public Class Sample
Dim condition As Boolean
Public Sub MySub() Public Sub MySub(Condition As Boolean)
If condition Then If Condition Then Exit Sub ' Noncompliant
Exit Sub ' Noncompliant ' ...
End If End Sub
For index = 1 To 10 Public Function MyFunction(Condition As Boolean) As Integer
If index = 5 Then If Condition Then
Exit For ' Noncompliant MyFunction = 42
End If Exit Function ' Noncompliant
' ... End If
Next
End Sub
Function MyFunction() As Object
' ... ' ...
MyFunction = 42
Exit Function ' Noncompliant
End Function End Function
End Class End Class
---- ----
@ -45,21 +33,17 @@ End Class
[source,vbnet] [source,vbnet]
---- ----
Public Class Sample Public Class Sample
Dim condition As Boolean
Public Sub MySub() Public Sub MySub(Condition As Boolean)
If condition Then If Condition Then Return ' Noncompliant
Return ' ...
End If End Sub
For index = 1 To 4 Public Function MyFunction(Condition As Boolean) As Integer
' ... If Condition Then Return 42
Next
End Sub
Function MyFunction() As Object
' ... ' ...
Return 42
End Function End Function
End Class End Class
---- ----