2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-16 15:42:52 +02:00
https://www.sonarsource.com/docs/CognitiveComplexity.pdf[Cognitive Complexity] Complexity is a measure of how hard the control flow of a method is to understand.
2020-06-30 12:48:39 +02:00
2023-06-16 15:42:52 +02:00
Methods with high Cognitive Complexity will be difficult to maintain.
2023-05-25 14:18:12 +02:00
2023-06-16 15:42:52 +02:00
[source,csharp,diff-id=1,diff-type=noncompliant]
2023-05-25 14:18:12 +02:00
----
2023-06-16 15:42:52 +02:00
int Abs(int n) // Noncompliant: cognitive complexity = 5
{
if (n >= 0) // +1
{
return n;
}
else // +2, due to nesting
{
if (n == int.MinValue) // +1
{
throw new ArgumentException("The absolute value of int.MinValue is outside of int boundaries");
}
else // +1
{
return -n;
}
}
}
2023-05-25 14:18:12 +02:00
----
2023-06-16 15:42:52 +02:00
They should be refactored to have lower complexity:
2023-05-25 14:18:12 +02:00
2023-06-16 15:42:52 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2023-05-25 14:18:12 +02:00
----
2023-06-16 15:42:52 +02:00
int Abs(int n) // Compliant: cognitive complexity = 3
{
if (n == int.MinValue) // +1
{
throw new ArgumentException("The absolute value of int.MinValue is outside of int boundaries");
}
else if (n >= 0) // +1
{
return n;
}
else // +1
{
return -n;
}
}
2023-05-25 14:18:12 +02:00
----
2023-06-16 15:42:52 +02:00
include::../resources.adoc[]
include::../rspecator-dotnet.adoc[]