51 lines
1.3 KiB
Plaintext
51 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
Methods with high Cognitive Complexity will be difficult to maintain.
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
They should be refactored to have lower complexity:
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
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;
|
|
}
|
|
}
|
|
----
|
|
|
|
include::../resources.adoc[]
|
|
include::../rspecator-dotnet.adoc[] |