2

I've been digging around and I can't get an answer that convinced me. Until recently I thought that the number of lines of code depend only on the complete lines of code, I mean, every line of code with a real purpose which is more or less what MSDN says that the count is based on the IL code; but then I ran into a case like this ...

public static System.Collections.Generic.IEnumerable<string> Test(System.Collections.Generic.IList<string> values)
{
    var listX = values.Where(x => !string.IsNullOrEmpty(x)).Select(y => y).Where(w => w.StartsWith("x"));
    return listX;
}

Code Metrics Result

...where the counter of lines of code counts 6 diferent lines. Can some one tell me what's really going on, how is that IL interpreted linq queries as it makes 3 diferent lines of a single line of code; even more how can I explain that the use of linq brakes the rule of amount of lines per method? Thanks

NetMage
  • 26,163
  • 3
  • 34
  • 55
jorge.armando
  • 50
  • 1
  • 7

1 Answers1

1

It appears the as part of using IL to approximate lines of codes, lambda expressions are counted as if they are separately defined methods.

Your sample LINQ query has 3 lambda expressions (one no effect Select and two Wheres that could be easily combined into one) each of which are compiled into a delegate.

The lines of code are counted as if written as follows:

static bool NotNullOrEmpty(string s) => !String.IsNullOrEmpty(s);
static string SelectSelf(string s) => s;
static bool StartsWithX(string s) => s.StartsWith("x");

public static System.Collections.Generic.IEnumerable<string> Test(System.Collections.Generic.IList<string> values)
{
    var listX = values.Where(NotNullOrEmpty).Select(SelectSelf).Where(StartsWithX);
    return listX;
}

Consider

public static System.Collections.Generic.IEnumerable<string> Test(System.Collections.Generic.IList<string> values) {
    var listX = values.Where(x => { return !string.IsNullOrEmpty(x); }).Select(y => { return y; }).Where(w => { var xs = "x"; return w.StartsWith(xs); }); return listX; }

How many lines of code should be counted?

NetMage
  • 26,163
  • 3
  • 34
  • 55