如何解决CA1502代码分析

时间:2014-01-20 10:16:51

标签: c# visual-studio-2012 code-analysis cyclomatic-complexity

根据代码分析结果,以下是警告消息

  
    

CA1502避免过度复杂化'METHOD()'的圈复杂度为27.重写或重构该方法以将复杂度降低到25.
    BusinessServices ReportService.cs 310

  

什么是圈复杂度以及如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

来自Wikipedia

  

源代码部分的圈复杂度是通过源代码的线性独立路径数量的计数。例如,如果源代码不包含诸如IF语句或FOR循环之类的决策点,则复杂性将为1,因为代码中只有一条路径。如果代码具有包含单个条件的单个IF语句,则代码中将有两条路径:一条路径,其中IF语句被评估为TRUE,一条路径,其中IF语句被评估为FALSE。

解决此问题的最简单方法是将方法分解为两个或多个较小的方法。 Visual Studio的内置重构工具(例如Refactor -> Extract Method)可用于将选定的代码部分提取到另一种方法中。

答案 1 :(得分:1)

CA1502是二进制分析仪。在某些情况下,您的代码并不那么复杂,也无法分解。这是导致CA1502警告的示例:

public class Mapping : Profile
{
    [SuppressMessage("Microsoft.Maintainability", "CA1502"]
    public Mapping()
    {
        CreateMap<ItemInstance, ManifestRecords>()
            .ForMember(dest => dest.SomeProperty1, opt => opt.MapFrom(src => src.SomeProperty1))
            .ForMember(dest => dest.SomeProperty2, opt => opt.MapFrom(src => src.SomeProperty2))
            .ForMember(dest => dest.SomeProperty3, opt => opt.MapFrom(src => src.SomeProperty3))
            .ForMember(dest => dest.SomeProperty4, opt => opt.MapFrom(src => src.SomeProperty4))
            .ForMember(dest => dest.SomeProperty5, opt => opt.MapFrom(src => src.SomeProperty5))
            .ForMember(dest => dest.SomeProperty6, opt => opt.MapFrom(src => src.SomeProperty6))
            .ForMember(dest => dest.SomeProperty7, opt => opt.MapFrom(src => src.SomeProperty7))
            .ForMember(dest => dest.SomeProperty8, opt => opt.MapFrom(src => src.SomeProperty8))
            .ForMember(dest => dest.SomeProperty9, opt => opt.MapFrom(src => src.SomeProperty9))
            .ForMember(dest => dest.SomeProperty10, opt => opt.MapFrom(src => src.SomeProperty10))
            .ForMember(dest => dest.SomeProperty11, opt => opt.MapFrom(src => src.SomeProperty11))
            .ForMember(dest => dest.SomeProperty12, opt => opt.MapFrom(src => src.SomeProperty12))
            .ForMember(dest => dest.SomeProperty13, opt => opt.MapFrom(src => src.SomeProperty13))
            .ForMember(dest => dest.SomeProperty14, opt => opt.MapFrom(src => src.SomeProperty14))
            .ForMember(dest => dest.SomeProperty15, opt => opt.MapFrom(src => src.SomeProperty15))
            .ForMember(dest => dest.SomeProperty16, opt => opt.MapFrom(src => src.SomeProperty16));
    }
}

您可以看到我正在使用AutoMapper,尽管在编译的二进制表示中可能存在某些复杂的源代码,但是在源代码中并没有什么复杂的循环复杂性。

您可以使用以下属性禁止显示警告:

[SuppressMessage("Microsoft.Maintainability", "CA1502"]