0

I have the following piece of code which checks if a particular DataRow has a column of a particular name and if it is not NULL.

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

Also I am processing the columns of a datarow and parsing it into corresponding datatypes.

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 shows this as cyclomatically complex. Is there any way to reduce the cyclomatic index on this function.

ckv
  • 10,539
  • 20
  • 100
  • 144
  • 1
    delete all that and use a proper strongly typed data model. That way there's no need to check if stuff has a certain other stuff with a certain name because you're working with strongly typed stuff rather than stringly typed dictionaries. – Federico Berasategui Dec 26 '14 at 09:05

2 Answers2

1

You could reduce the cyclomatic complexity a tad by simply returning the chained AND statements:

private static bool HasValue(DataColumn c, DataRow row)
{
    return c != null && row != null && row[c.ColumnName] != DBNull.Value;
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

Instead of looping through row.Table.Columns to find out if table contains a column, you can do this:

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

This eliminates the loop and switch within it and reduces the cyclomatic complexity of your function significantly.

brz
  • 5,926
  • 1
  • 18
  • 18