分享

微软内部代码检查工具 StyleCop 最新版(Microsoft Source Analysis for C#)

 高高 2011-07-01

微软内部代码检查工具 StyleCop 最新版(Microsoft Source Analysis for C#)

引言:SourceAnalysis (StyleCop)的终极目标是让所有人都能写出优雅和一致的代码,因此这些代码具有很高的可读性。

早就听说了微软内部的静态代码检查和代码强制格式美化工具 StyleCop ,昨天(2008-05-23)微软在 MSDN Code Gallery 发布了 4.2 版本,并命名为 Microsoft Source Analysis for C#  。

SourceAnalysis (StyleCop)不是代码格式化(代码美化)工具,而是代码规范检查工具(Code Review 工具),它不仅仅检查代码格式,而是编码规范,包括命名和注释等。

SourceAnalysis (StyleCop)目的是帮助项目团队执行一系列常用的源代码格式规范,这些规范是关于如何开发布局规整,易读,易维护并且文档良好的优雅代码的 (help teams enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code)。

SourceAnalysis (StyleCop) 现在包含了 200 个左右的最佳实践规则(best practice rules),这些规则与 Visual Studio 2005 和  Visual Studio 2008 中默认的代码格式化规则是一致的。

SourceAnalysis (StyleCop)可以作为 Visual studio 的插件运行,在VS中(我的是2008)对一个C#文件点击右键后的:

runSourceAnalysis

 

在VS执行后,执行效果如下:

sourceAnalysis

同时 SourceAnalysis (StyleCop)也可以作为 MSBuild 任务(安装时有选项)通过命令行执行。

从 我现在的了解,SourceAnalysis (StyleCop)只是一个代码格式的检查工具,它会根据预定义的C#代码格式的最佳实践,对我们的源代码进行检查,并给出不符合编码风格的错误提示。 这一点来说与微软的另一个代码检查工具 FxCop 很相似,但 FxCop 是对 dll (compiled binaries) 进行检查,所以 FxCop 适用于新项目通过持续集成工具来使用的情况。也就是说 FxCop 是项目级别的,而 SourceAnalysis (StyleCop)是代码级别的,更适合于程序员在编程过程中使用。

与 FxCop 的另一个不同是,SourceAnalysis (StyleCop)不提供灵活的规则设置,而是使用所谓 one-size-fits-all 的方式强制人们用同样的习惯书写代码,因此 SourceAnalysis (StyleCop)的终极目标是:The ultimate goal of Source Analysis is to allow you to produce elegant, consistent code that your team members and others who view your code will find highly readable.

SourceAnalysis (StyleCop)检查的规则包括:

  • 布局(Layout of elements, statements, expressions, and query clauses )
  • 括号位置(Placement of curly brackets, parenthesis, square brackets, etc )
  • 空格(Spacing around keywords and operator symbols )
  • 行距(Line spacing )
  • 参数位置(Placement of method parameters within method declarations or method calls )
  • 元素标准排列(Standard ordering of elements within a class )
  • 注释格式(Formatting of documentation within element headers and file headers )
  • 命名(Naming of elements, fields and variables )
  • 内置类型的使用(Use of the built-in types )
  • 访问修饰符的使用(Use of access modifiers )
  • 文件内容(Allowed contents of files )
  • Debugging文本(Debugging text)

    还没有真正在项目中使用,这些规则去什么地方找,如何修改还不清楚,以后使用了再说。

    开 始使用这些工具时可能会觉得对我们要求太苛刻,但根据微软自己的经验:after a short adjustment period, they came to appreciate the rules enforced by Source Analysis, and even began to find it difficult to read code not written in this style.

    参考与下载:

    StyleCop: Announcing the release of Microsoft Source Analysis for C#

    FxCop:Code Analysis and Code Metrics

    代码规范:Microsoft .NET 类库开发的设计准则

    • 本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
      转藏 分享 献花(0

      0条评论

      发表

      请遵守用户 评论公约

      类似文章 更多