Why is the cyclomatic complexity of these methods so high?

Metrics are calculated using Visual Studio.

The first method has CC = 4

private IEnumerable<string> GetRows(DataTable dt, string columnDelimiter) { return from DataRow row in dt.Rows select string.Join(columnDelimiter, row.ItemArray.Select(k => k.ToString())); } 

The second method has CC = 5.

  private IEnumerable<string> GetRowsForeach(DataTable dt, string columnDelimiter) { var rows = new List<string>(); foreach (DataRow row in dt.Rows) { var rowString = string.Join(columnDelimiter, row.ItemArray.Select(k => k.ToString())); rows.Add(rowString); } return rows; } 

I would say that the first method should have CC = 1, and the second, perhaps CC = 1 or maybe 2 (understanding foreach as with the final condition, but I would never say that their CC is so high that I do not understand? / p>

+6
source share
2 answers

This is an imperfect tool. He sees IL, the code generated by the C # compiler. He does not see your code. And in C # there is a lot of syntactic sugar that was designed to make your code easy to understand, but has an iceberg of code-gen below the water line. Query concepts certainly follow this pattern.

Use CC only as a guide, never let him set the rules and never let him squeeze your style. Your brain surpasses any tool.

+3
source

Apparently, this is due to the fact that each IEnumerator generated using linq methods also implements IDisposable, which, in order to be released correctly, will transfer the code to the try..catch block.

there is a good explanation here.

In the first example, you have two select statements along with the join, hence counter 4.

+2
source

All Articles