rspec/rules/S2259/vbnet/rule.adoc

74 lines
1.8 KiB
Plaintext
Raw Normal View History

A reference to `Nothing` should never be dereferenced/accessed. Doing so will cause a `NullReferenceException` to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.
== Noncompliant Code Example
[source,vbnet]
----
Public Sub Method()
Dim O As Object = Nothing
Console.WriteLine(O.ToString) ' Noncompliant, always Nothing
End Sub
----
== Compliant Solution
[source,vbnet]
----
Public Sub Method()
Dim O As New Object
Console.WriteLine(O.ToString)
End Sub
----
== Exceptions
Calls to extension methods are not reported because they can still operate on `Nothing` values.
To create a custom null validation method declare an attribute with name `ValidatedNotNullAttribute` and mark the parameter that is validated for null in your method declaration with it:
[source,vbnet]
----
Public NotInheritable Class ValidatedNotNullAttribute
Inherits Attribute
End Class
Public Module Guard
Public Sub CheckNotNull(Of T)(<ValidatedNotNull> Value As T, Name As String)
If Value Is Nothing Then Throw New ArgumentNullException(Name)
End Sub
End Module
Public Class Sample
Public Sub Log(Value As Object)
CheckNotNull(Value, NameOf(Value))
If Value Is Nothing Then
Console.WriteLine(Value.ToString) ' Compliant, this code is not reachable
End If
End Sub
End Class
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]