代碼審查工具StyleCop

“代碼審查”或是“代碼評審”(Code Review),這是一個流程,當開發人員寫好代碼後,需要讓別人來review一下他的代碼,這是一種有效發現BUG的方法。由此,我們可以審查代碼的風格、邏輯、思路……,找出問題,以及改進代碼。因爲這是代碼剛剛出爐的時候,所以,這也是代碼重構,代碼調整,代碼修改的最佳時候。所以,Code Review是編碼實現中最最重要的一個環節。

長時間以來,Code Review需要有一些有效的工具來支持,這樣我們就可以更容易,更有效率地來進行代碼審查工作。

StyleCop是代碼規範檢查工具(Code Review 工具),它不僅僅檢查代碼格式,而是編碼規範,包括命名和註釋等。StyleCop可以幫助你更容易地進行這項活動。StyleCop現在包含了 200 個左右的最佳實踐規則(best practice rules),這些規則與 Visual Studio 2005 和  Visual Studio 2008 中默認的代碼格式化規則是一致的。它會根據預定義的C#代碼格式的最佳實踐,對我們的源代碼進行檢查,並給出不符合編碼風格的錯誤提示。這一點來說與微軟的另一個代碼檢查工具 FxCop 很相似,但 FxCop 是對 dll (compiled binaries) 進行檢查,所以 FxCop 適用於新項目通過持續集成工具來使用的情況。也就是說 FxCop 是項目級別的,而 StyleCop是代碼級別的,更適合於程序員在編程過程中使用。

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)

常用規則

基礎

Invalid spacing around the comma :’,’後面需要加空格(幾個無所謂)

Invalid spacing around the opening curly bracket:’{‘前後需要加空格(僅僅一個,要不然就報’The code contains multiple spaces in a row. Only one space is needed’)

Invalid spacing around the closing curly bracket: ‘}’前面需要加空格(同上)

All using directives must be placed inside of the namespace: using指令需要移到命名空間內

例如:

複製代碼
using System; using System.Text;
Namespace StyleCopDemo {       Public class Person       {       } } //應該爲Namespace StyleCopDemo {      using System;      using System.Text;
     Public Class Person      {      } }
複製代碼

這個我也有點暈了!不過有一篇文章http://blogs.msdn.com/b/abhinaba/archive/2006/08/21/709051.aspx,介紹了這樣做的好處!

Adjacent elements must be separated by a blank line:緊鄰的元素之間必須用空格行隔開,例如using命名空間和namespace之間。

An opening curly bracket must not be followed by a blank line: ‘{‘下面一行不允許是空行

A closing curly bracket must not be preceded by a blank line: ‘}’上面一行不允許是空行

Using directives must be sorted alphabetically by the namespaces:using語句必須要按照字母排序(順序)

The code must not contain multiple blank lines in a row:代碼中不允許一行中有多行空行。

錯誤:

正確爲:

文檔規範:

The class must have a documentation header:定義的類必須含有文件頭標誌’///’而且其中的內容介紹最好是帶有空格的(有點變態),不然可能會報’ The documentation text within the summary tag does not contain any whitespace between words, indicating that it most likely does not follow a proper grammatical structure required for documentation text’,例如:

複製代碼
    /// <summary>/// 用戶類 用戶基本信息     /// </summary>    public class Person     {     }
複製代碼

The file has no header, the header Xml is invalid, or the header is not located at the top of the file:

需要在文件開頭上加:

複製代碼
//------------------------------------------------------- //    <copyright file="Person.cs" company="MyCompany"> //             Copyright MyCompany. All rights reserved. //    </copyright> //-------------------------------------------------------
複製代碼

注意縮進格式。

A C# document may only contain a single class at the root level unless all of the classes are partial and are of the same type:【猜】C#文檔一般只能包含對一個類的描述。除非這些類是partial類型或者是同類型的。這種錯誤一般是在一個*.cs文件中有多個不同類型的類。

函數規範:

The method must have an access modifier:方法需要訪問修飾符(public private protected..)

The method must have a documentation header:方法必須要文檔說明就是以‘///’開頭的。

‘///’規範要求:

標籤內的內容不允許爲空。內容最好是用空格隔開否則會報‘The documentation text within the summary tag does not contain any whitespace between words, indicating that it most likely does not follow a proper grammatical structure required for documentation text’;

實例:

 

字段規範:

The field must have an access modifier:字段必須要有修飾符

Variable names must start with a lower-case letter:字段的名字必須是小寫開頭的

The field must have a documentation header:字段必須要有文檔說明,以///開頭的

有些程序員喜歡以_開頭來命名字段,但是StyleCop是不推薦的。(Field names must not start with an underscore)

StyleCop放在 http://stylecop.codeplex.com/,最新版本是2012年7月5日發佈 4.7.44版本。更多的信息可以關注StyleCop開發團隊的blog:http://blogs.msdn.com/sourceanalysis

StyleCop提供了簡單和有效的方式來對項目的代碼編寫風格進行檢查。StyleCop可以多種方式運行,可以插件的方式在Visual Studio的IDE中運行;也可以MSBuild任務的方式運行,可整合到程序構建流程中;或者以命令行的方式運行,可針對一個或多個代碼文件進行檢查。

StyleCop的命令行使用方法:

Usage:    StyleCopCmd [options] [path]

Options:    -a         Process all source files found under the start path (default)    -cs {file} Analyze the specified file.    -f         Perform a full analyze (ignore cached results)    -u         Do not write results cache files.    -o {file}  Apply the given StyleCop options file to all projects and files    -l {file}  Save violation report at the given location. If omitted, saves               StyleCopViolations.xml in the current directory.    -p {path}  Attempts to discover StyleCop AddIn modules under the given               path. This flag may be specified multiple times to search under               multiple paths    -i         Ignore the default StyleCop AddIn path under the All Users\Applica tion Data folder

Conditional Compilation Flags:    -define:FLAG1;FLAG2;FLAG3

Path:    Specifies the path to begin search for source files.    If this is omitted, uses the current directory as the    start path.

CodeProject上有一篇文章詳細的講述StyleCop的使用方法 C# Code Reviews using StyleCop – Detailed Article

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章