Using FirstOrDefault
or SingleOrDefault
on collections that are known to be non-empty is an issue due to:
- Code Clarity and intent: When you use
FirstOrDefault
or SingleOrDefault
, it implies that the collection might be
empty, which can be misleading if you know it is not. It can be confusing for other developers who read your code, making it harder for them to
understand the actual constraints and behavior of the collection. This leads to confusion and harder-to-maintain code.
- Error handling: If the developer’s intend is for the collection not to be empty, using
FirstOrDefault
and
SingleOrDefault
can lead to subtle bugs. These methods return a default value (null
for reference types and
default
for value types) when the collection is empty, potentially causing issues like NullReferenceException
later in the
code. In contrast, First
or Single
will throw an InvalidOperationException
immediately if the collection is
empty, making it easier to detect and address issues early in the development process.
- Code coverage: Potentially, having to check if the result is
null
, you introduces a condition that cannot be fully tested,
impacting the code coverage.
Code examples
Noncompliant code example
Dim Items As New list(Of Integer) From {1, 2, 3}
Dim FirstItem As Integer = Items.FirstOrDefault() ' Noncompliant, this implies the collection might be empty, when we know it is not
Compliant solution
Dim Items As New list(Of Integer) From {1, 2, 3}
Dim FirstItem As Integer = Items.First() ' Compliant