【问题标题】:Reduce Cyclomatic complexity while processing DataRows在处理 DataRows 时降低圈复杂度
【发布时间】:2014-12-26 09:00:53
【问题描述】:

我有以下代码检查特定 DataRow 是否具有特定名称的列以及它是否不为 NULL。

private static bool HasValue(DataColumn c, DataRow row)
{
     if (c != null && row != null && row[c.ColumnName] != System.DBNull.Value)
     {
         return true;
     }
     return false;
}

我还在处理数据行的列并将其解析为相应的数据类型。

foreach (DataColumn c in row.Table.Columns)
{
     switch (c.ColumnName)
     {
     case Constants.Literals.ACTIVATIONDATETIME:
                                if (HasValue(c, row))
                                {
                                    bFound = true; credentialInfo.ActivationDateTime = DateTimeOffset.Parse(Convert.ToString(row[c.ColumnName]));
                                }
                                break;
     }
}

Visual Studio 将其显示为圈复杂。有什么办法可以减少这个函数的圈指数。

【问题讨论】:

  • 删除所有这些并使用适当的强类型数据模型。这样就不需要检查东西是否有其他具有特定名称的东西,因为您正在使用强类型的东西而不是字符串类型的字典。

标签: c# cyclomatic-complexity


【解决方案1】:

您可以这样做:

var column = row.Table.Columns[Constants.Literals.ACTIVATIONDATETIME];
if(HasValue(column, row))
{
     //column found.
}

这消除了其中的循环和切换,并显着降低了函数的圈复杂度。

【讨论】:

    【解决方案2】:

    您可以通过简单地返回链接的 AND 语句来降低圈复杂度 一点点

    private static bool HasValue(DataColumn c, DataRow row)
    {
        return c != null && row != null && row[c.ColumnName] != DBNull.Value;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      相关资源
      最近更新 更多