在具有13个事件处理程序订阅的方法中,圈复杂度如何变为27? [英] How can the cyclomatic complexity be 27 in a method with 13 event handler subscriptions?

查看:91
本文介绍了在具有13个事件处理程序订阅的方法中,圈复杂度如何变为27?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下代码,排序:

  private void InitializeEvents()
{
this。事件1 + =(s,e)=> {};
this.Event2 + =(s,e)=> {};
this.Event3 + =(s,e)=> {};
this.Event4 + =(s,e)=> {};
this.Event5 + =(s,e)=> {};
this.Event6 + =(s,e)=> {};
this.Event7 + =(s,e)=> {};
this.Event8 + =(s,e)=> {};
this.Event9 + =(s,e)=> {};
this.Event10 + =(s,e)=> {};
this.Event11 + =(s,e)=> {};
this.Event12 + =(s,e)=> {};
this.Event13 + =(s,e)=> {}; VS10 Ultimate中的代码分析说圈复杂度为27。删除其中一条线会导致圈复杂度25。



没有分支在进行,这怎么可能?

解决方案

请记住,代码分析正在查看程序集中的IL,而不是源代码。 IL中没有原生支持lambda表达式的内容,因此它们是编译器的构造。您可以在此处中找到输出的详细信息。但基本上,您的lambda表达式会变成一个匿名的私有私有类。但是,不是每次在代码中引用匿名创建对象时都创建一个实例,而是缓存了该创建对象。因此,每次分配lambda表达式时,它都会执行一次检查以查看该lambda deligate的实例是否已创建,如果这样,它将使用缓存的deligate。这会在IL中生成if / else,从而使复杂度增加2。因此,在此函数中,复杂度为1 + 2 *(lambda express)= 1 + 2 *(13)= 27,这是正确的数字。


We have this code, sortof:

private void InitializeEvents()
{
    this.Event1 += (s,e) => { };
    this.Event2 += (s,e) => { };
    this.Event3 += (s,e) => { };
    this.Event4 += (s,e) => { };
    this.Event5 += (s,e) => { };
    this.Event6 += (s,e) => { };
    this.Event7 += (s,e) => { };
    this.Event8 += (s,e) => { };
    this.Event9 += (s,e) => { };
    this.Event10 += (s,e) => { };
    this.Event11 += (s,e) => { };
    this.Event12 += (s,e) => { };
    this.Event13 += (s,e) => { };
}

Code analysis in VS10 Ultimate says "cyclomatic complexity of 27". Removing one of the lines makes the cyclomatic complexity 25.

There's no branching going on, so how is this possible?

解决方案

Remeber that the Code Analysis is looking at the IL in your assembly, not your source code. There is nothing in the IL that natively supports lambda expressions, so they are a construct of the compiler. You can find the specifics of what is ouput here. But basically your lambda expression is turned into a private static class that is an anonymous deligate. However, rather that create an instance of the anonymous deligate every time it is referenced in code, the deligate is cached. So each time you assign a lambda expression, it does a check to see an instance of that lambda deligate has been created, if so it uses the cached deligate. That generates an if/else in the IL increasing the complexity by 2. So in this functions complexity is 1 + 2*(lambda express) = 1 + 2 *(13) = 27 which is the correct number.

这篇关于在具有13个事件处理程序订阅的方法中,圈复杂度如何变为27?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆