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#文件點擊右鍵後的:

微軟內部代碼檢查工具Microsoft Source Analysis for C#

  在VS執行後,執行效果如下:

微軟內部代碼檢查工具Microsoft Source Analysis for C#

  圖片看不清楚?請點擊這裏查看原圖(大圖)。

  同時 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 類庫開發的設計準則

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