rspec/rules/S1155/csharp/rule.adoc

58 lines
1.6 KiB
Plaintext
Raw Normal View History

2022-01-18 07:48:34 +01:00
Using `.Count()` to test for emptiness works, but using `.Any()` makes the intent clearer, and the code more readable. However, there are some cases where special attention should be paid:
2021-01-06 17:38:34 +01:00
2022-01-18 07:48:34 +01:00
* if the collection is an `EntityFramework` or other ORM query, calling `.Count()` will cause executing a potentially massive SQL query and could put a large overhead on the application database. Calling `.Any()` will also connect to the database, but will generate much more efficient SQL.
* if the collection is part of a LINQ query that contains `.Select()` statements that create objects, a large amount of memory could be unnecessarily allocated. Calling `.Any()` will be much more efficient because it will execute fewer iterations of the enumerable.
2020-06-30 12:47:33 +02:00
== Noncompliant Code Example
----
private static bool HasContent(IEnumerable<string> strings)
{
return strings.Count() > 0; // Noncompliant
}
private static bool HasContent2(IEnumerable<string> strings)
{
return strings.Count() >= 1; // Noncompliant
}
private static bool IsEmpty(IEnumerable<string> strings)
{
return strings.Count() == 0; // Noncompliant
}
----
== Compliant Solution
----
private static bool HasContent(IEnumerable<string> strings)
{
return strings.Any();
}
2022-01-18 07:48:34 +01:00
private static bool HasContent2(IEnumerable<string> strings)
{
return strings.Any();
}
2020-06-30 12:47:33 +02:00
private static bool IsEmpty(IEnumerable<string> strings)
{
return !strings.Any();
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]