Visual Studio中的代码指标分析器以及代码指标电源工具,将以下代码的TestMethod
方法中的代码行数报告为8。
最多,我希望它能将代码行报告为3。
[TestClass]
public class UnitTest1
{
private void Test(out string str)
{
str = null;
}
[TestMethod]
public void TestMethod()
{
var mock = new Mock<UnitTest1>();
string str;
mock.Verify(m => m.Test(out str));
}
}
任何人都可以解释为什么会这样吗?
更多信息
经过一番挖掘后,我发现从Test方法中删除out
参数并更新测试代码会导致LOC报告为2,我认为这是正确的。添加out
会导致跳转,因此不是因为大括号或属性。
使用dotPeek反编译DLL会显示由于out
参数生成的大量额外代码,这些参数可被视为8 LOC,但删除参数和反编译也会显示生成的代码,可以将其视为5 LOC,所以这不仅仅是VS计算编译器生成的代码(我不相信它应该做的事情)。
答案 0 :(得分:2)
“行代码”(LOC)有几种常见的定义。每个人都试图将我认为是一个几乎毫无意义的指标。例如谷歌的有效代码行(eLOC)。
我认为VS将属性作为方法声明的一部分包含在内,并试图通过计算语句甚至括号来给eLOC。一种可能性是'm =&gt; m.Test(out str)'被视为陈述。
考虑一下:
if (a > 1 &&
b > 2)
{
var result;
result = GetAValue();
return result;
}
和此:
if (a> 1 && b >2)
return GetAValue();
LOC的一个定义是计算具有任何代码的行。这甚至可能包括牙箍。在如此极端简单的定义中,计数在编码风格上存在巨大差异。
eLOC试图减少或消除代码风格的影响。例如,在这种情况下,声明可以被计为“行”。没有理由,只是解释。
考虑一下:
int varA = 0;
varA = GetAValue();
和此:
var varA = GetAValue();
两行还是一行?
这一切都取决于意图。如果要测量您需要的显示器的高度,那么可能使用简单的LOC。如果目的是衡量复杂性,那么计算代码语句可能更好,例如eLOC。
如果您想衡量复杂性,请使用复杂性指标,如圈复杂度。不要担心VS如何测量LOC,我认为,无论如何,它都是无用的指标。
答案 1 :(得分:2)
使用工具NDepend,TestMethod()
的#行代码(LoC)为2。 (免责声明我是此工具的开发者之一)。我写了一篇关于How do you count your number of Lines Of Code (LOC) ?的文章,该文章揭示了什么是逻辑 LoC,以及所有 .NET LoC计数工具如何依赖于 PDB序列要点技术。
我对由VS度量提供的这个LoC值为8的猜测是,它包括由lambda表达式生成的方法的LoC +它包括与开放/结束括号相关的PDB序列点(NDepend没有&#39; T)。编译器还完成了大量的体操操作来执行所谓的capturing the local variable str
,但这不应该影响从PDB序列点推断的#LoC。
顺便说一下,我写了另外两篇与LoC相关的文章:
答案 2 :(得分:0)
我想知道Visual Studio的行数以及为什么我所看到的不是所报告的。因此,我编写了一个小型C#控制台程序来计算纯代码行,并将结果写入CSV文件(请参见下文)。
打开一个新的解决方案,将其复制并粘贴到Program.cs文件中,生成可执行文件,然后就可以开始了。这是一个.Net 3.5应用程序。将其复制到代码库的最顶层目录中。打开命令窗口并运行可执行文件。您会得到两个提示,首先是程序/子系统的名称,以及要分析的任何其他文件类型。然后将结果写入当前目录中的CSV文件。对于您的目的或交给管理人员来说,这是一件很简单的事情。
Anyhoo,这是FWIW和YMMV:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace CodeMetricsConsole
{
class Program
{
// Concept here is that the program has a list of file extensions to do line counts on; it
// gets any extra extensions at startup from the user. Then it gets a list of files based on
// each extension in the current directory and all subdirectories. Then it walks through
// each file line by line and will display counts for that file and for that file extension.
// It writes that information to a CSV file in the current directory. It uses regular expressions
// on each line of each file to figure out what it's looking at, and how to count it (i.e. is it
// a line of code, a single or multi line comment, a multi-line string, or a whitespace line).
//
static void Main(string[] args)
{
try
{
Console.WriteLine(); // spacing
// prompt user for subsystem or application name
String userInput_subSystemName;
Console.Write("Enter the name of this application or subsystem (required): ");
userInput_subSystemName = Console.ReadLine();
if (userInput_subSystemName.Length == 0)
{
Console.WriteLine("Application or subsystem name required, exiting.");
return;
}
Console.WriteLine(); // spacing
// prompt user for additional types
String userInput_additionalFileTypes;
Console.WriteLine("Default extensions are asax, css, cs, js, aspx, ascx, master, txt, jsp, java, php, bas");
Console.WriteLine("Enter a comma-separated list of additional file extensions (if any) you wish to analyze");
Console.Write(" --> ");
userInput_additionalFileTypes = Console.ReadLine();
// tell user processing is starting
Console.WriteLine();
Console.WriteLine("Getting LOC counts...");
Console.WriteLine();
// the default file types to analyze - hashset to avoid duplicates if the user supplies extensions
HashSet allowedExtensions = new HashSet { "asax", "css", "cs", "js", "aspx", "ascx", "master", "txt", "jsp", "java", "php", "bas" };
// Add user-supplied types to allowedExtensions if any
String[] additionalFileTypes;
String[] separator = { "," };
if (userInput_additionalFileTypes.Length > 0)
{
// split string into array of additional file types
additionalFileTypes = userInput_additionalFileTypes.Split(separator, StringSplitOptions.RemoveEmptyEntries);
// walk through user-provided file types and append to default file types
foreach (String ext in additionalFileTypes)
{
try
{
allowedExtensions.Add(ext.Trim()); // remove spaces
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
// summary file to write to
String summaryFile = userInput_subSystemName + "_Summary.csv";
String path = Directory.GetCurrentDirectory();
String pathAndFile = path + Path.DirectorySeparatorChar + summaryFile;
// regexes for the different line possibilities
Regex oneLineComment = new Regex(@"^\s*//"); // match whitespace to two slashes
Regex startBlockComment = new Regex(@"^\s*/\*.*"); // match whitespace to /*
Regex whiteSpaceOnly = new Regex(@"^\s*$"); // match whitespace only
Regex code = new Regex(@"\S*"); // match anything but whitespace
Regex endBlockComment = new Regex(@".*\*/"); // match anything and */ - only used after block comment detected
Regex oneLineBlockComment = new Regex(@"^\s*/\*.*\*/.*"); // match whitespace to /* ... */
Regex multiLineStringStart = new Regex("^[^\"]*@\".*"); // match @" - don't match "@"
Regex multiLineStringEnd = new Regex("^.*\".*"); // match double quotes - only used after multi line string start detected
Regex oneLineMLString = new Regex("^.*@\".*\""); // match @"..."
Regex vbaComment = new Regex(@"^\s*'"); // match whitespace to single quote
// Uncomment these two lines to test your regex with the function testRegex() below
//new Program().testRegex(oneLineMLString);
//return;
FileStream fs = null;
String line = null;
int codeLineCount = 0;
int commentLineCount = 0;
int wsLineCount = 0;
int multiLineStringCount = 0;
int fileCodeLineCount = 0;
int fileCommentLineCount = 0;
int fileWsLineCount = 0;
int fileMultiLineStringCount = 0;
Boolean inBlockComment = false;
Boolean inMultiLineString = false;
try
{
// write to summary CSV file, overwrite if exists, don't append
using (StreamWriter outFile = new StreamWriter(pathAndFile, false))
{
// outFile header
outFile.WriteLine("filename, codeLineCount, commentLineCount, wsLineCount, mlsLineCount");
// walk through files with specified extensions
foreach (String allowed_extension in allowedExtensions)
{
String extension = "*." + allowed_extension;
// reset accumulating values for extension
codeLineCount = 0;
commentLineCount = 0;
wsLineCount = 0;
multiLineStringCount = 0;
// Get all files in current directory and subdirectories with specified extension
String[] fileList = Directory.GetFiles(Directory.GetCurrentDirectory(), extension, SearchOption.AllDirectories);
// walk through all files of this type
for (int i = 0; i < fileList.Length; i++)
{
// reset values for this file
fileCodeLineCount = 0;
fileCommentLineCount = 0;
fileWsLineCount = 0;
fileMultiLineStringCount = 0;
inBlockComment = false;
inMultiLineString = false;
try
{
// open file
fs = new FileStream(fileList[i], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (TextReader tr = new StreamReader(fs))
{
// walk through lines in file
while ((line = tr.ReadLine()) != null)
{
if (inBlockComment)
{
if (whiteSpaceOnly.IsMatch(line))
{
fileWsLineCount++;
}
else
{
fileCommentLineCount++;
}
if (endBlockComment.IsMatch(line)) inBlockComment = false;
}
else if (inMultiLineString)
{
fileMultiLineStringCount++;
if (multiLineStringEnd.IsMatch(line)) inMultiLineString = false;
}
else
{
// not in a block comment or multi-line string
if (oneLineComment.IsMatch(line))
{
fileCommentLineCount++;
}
else if (oneLineBlockComment.IsMatch(line))
{
fileCommentLineCount++;
}
else if ((startBlockComment.IsMatch(line)) && (!(oneLineBlockComment.IsMatch(line))))
{
fileCommentLineCount++;
inBlockComment = true;
}
else if (whiteSpaceOnly.IsMatch(line))
{
fileWsLineCount++;
}
else if (oneLineMLString.IsMatch(line))
{
fileCodeLineCount++;
}
else if ((multiLineStringStart.IsMatch(line)) && (!(oneLineMLString.IsMatch(line))))
{
fileCodeLineCount++;
inMultiLineString = true;
}
else if ((vbaComment.IsMatch(line)) && (allowed_extension.Equals("txt") || allowed_extension.Equals("bas"))
{
fileCommentLineCount++;
}
else
{
// none of the above, thus it is a code line
fileCodeLineCount++;
}
}
} // while
outFile.WriteLine(fileList[i] + ", " + fileCodeLineCount + ", " + fileCommentLineCount + ", " + fileWsLineCount + ", " + fileMultiLineStringCount);
fs.Close();
fs = null;
} // using
}
finally
{
if (fs != null) fs.Dispose();
}
// update accumulating values
codeLineCount = codeLineCount + fileCodeLineCount;
commentLineCount = commentLineCount + fileCommentLineCount;
wsLineCount = wsLineCount + fileWsLineCount;
multiLineStringCount = multiLineStringCount + fileMultiLineStringCount;
} // for (specific file)
outFile.WriteLine("Summary for: " + extension + ", " + codeLineCount + ", " + commentLineCount + ", " + wsLineCount + ", " + multiLineStringCount);
} // foreach (all files with specified extension)
} // using summary file streamwriter
Console.WriteLine("Analysis complete, file is: " + pathAndFile);
} // try block
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
catch (Exception e2)
{
Console.WriteLine("Error: " + e2.Message);
}
} // main
// local testing function for debugging purposes
private void testRegex(Regex rx)
{
String test = " asdfasd asdf @\" adf ++--// /*\" ";
if (rx.IsMatch(test))
{
Console.WriteLine(" -->| " + rx.ToString() + " | matched: " + test);
}
else
{
Console.WriteLine("No match");
}
}
} // class
} // namespace
这是它的工作方式:
是的,彼此嵌入了三个循环(O(n-cubed)O_O),但这只是一个简单的独立开发人员工具,我运行的最大代码库约为35万行,这花了在Core i7上运行需要10秒。
编辑:只需在Firefox 12代码库上运行它,就可以使用AMD Phenom处理器运行大约430万行(330万行代码,100万条注释),大约21000个文件-耗时7分钟,观看了任务管理器中的“性能”选项卡,没有压力。仅供参考。
我的态度是,如果我将其编写为送入编译器的指令的一部分,则这是一行代码,应计入在内。
可以轻松地对其进行自定义,以忽略或计算所需的任何内容(括号,名称空间,文件顶部的包含等)。只需添加正则表达式,使用正则表达式下方的功能对其进行测试,然后使用该正则表达式更新if语句。