C# S138, S1541 and S3776 include local functions when evaluating parent

Sonar Analyzer: 7.13, c#

If a function uses the c# 7 local functions feature, when counting the number of lines in the parent function, the lines of the child functions are also included. e.g.

void a() 
{
    b();
    c();

    void b() 
    {  
        //40 lines here
    }
    void c() 
    {  
        //40 lines here
    }
}

Will report that function a() contains more than 80 lines, triggering rule S138. If b() and c() are made siblings of a() instead of children this doesn’t happen but that is a poorer code quality as it gives b() and c() greater visibility than is needed.

It will also incorrectly include the definitions of b() and c() as part of a() when processing rule S3776 to compute the Cognitive Complexity and S1541 to compute cyclomatic complexity of a().

1 Like

thank you, @paulhickman. I agree with you and I’ve opened #2470 to have it on the radar.

I agree with you that just extracting the local function into a private method is just a please the tool hack which should be avoided.

We’ll need to discuss internally if we would ignore the local function or have a separate metric for it. I guess we could just make the rules you’ve mentioned ignore local functions, and create a separate rule to avoid having too many local functions / calls to private methods. WDYT, @paulhickman?