Why is this an issue?
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.
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:
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;
}
}
Resources
Documentation