[Tool] 使用CodeMaid自動程式排版

摘要:[Tool] 使用CodeMaid自動程式排版

[Tool] 使用CodeMaid自動程式排版

前言

「使用StyleCop驗證命名規則」這篇文章,指引開發人員透過StyleCop這個工具,來自動檢驗專案中產出的程式碼是否合乎命名規則。

但是在專案開發的過程中,如果只是驗證命名規則、而沒有統一程式排版,專案中很容易就會出現類似下列範例的程式碼產出。這樣的產出,雖然能夠正常地提供專案功能、並且符合微軟的命名規則,但是因為程式排版凌亂的問題,大幅降低了這份程式碼的可維護性。

  • Bad Code

    public class Class1
    {
        private string _name = "Clark";
    
        public string GetResult()
        {
            return (_count01 + _count02).ToString();
        }
    
    
    
    
        private int _count01 = 1;
    
        private int _count03 = 3;
    
        public string GetName()
        {
            return _name;
        }
    
        private int _count02 = 2;
    }
    

本篇文章介紹如何透過CodeMaid這個工具,來自動整理專案中程式碼的排版,在不增加開發人員負擔的前提下,讓團隊的程式碼產出趨於一致、大幅提高程式碼的生產品質。主要為自己留個紀錄,也希望能幫助到有需要的開發人員。

  • Good Code

    public class Class1
    {
        private int _count01 = 1;
        private int _count02 = 2;
        private int _count03 = 3;
        private string _name = "Clark";
    
        public string GetName()
        {
            return _name;
        }
    
        public string GetResult()
        {
            return (_count01 + _count02).ToString();
        }
    }
    

安裝

  1. 首先至微軟的官方網站,下載CodeMaid安裝檔:「CodeMaid_v0.7.4.vsix」。

    安裝01

  2. 執行CodeMaid安裝檔:「CodeMaid_v0.7.4.vsix」,來安裝CodeMaid。

    安裝02

執行

  1. 使用Visual Studio開啟專案。

    執行01

  2. Visual Studio上方工具列中,開啟CODEMAID選單、點選Configuration來開啟CodeMaid設定畫面。

    執行02

  3. CodeMaid設定畫面中,進入Reorganizing->General設定頁面,勾選「Run organize at start cleanup」後,點擊Save按鈕完成設定。

    執行03

  4. 後續就可以從Visual Studio上方工具列中,開啟CODEMAID選單、點選「Cleanup all Code」來自動排版專案內的所有程式碼。

    執行04

  5. 自動排版功能執行結束之後,開啟專案內的程式碼,會發現程式碼內容已經排列整齊,大幅提高程式碼的可維護性。

    執行05

延伸

CodeMaid所提供的程式碼自動排版功能,用起來很方便、排版結果也很簡潔。但是在一些細節上,總是會有些許的排版定義,不符合團隊成員對於程式碼品質的要求。不過還好的是,CodeMaid開放了許多排版條件的設定項目,讓開發人員可以調整排版條件,來讓排版結果趨近於團隊成員對程式碼產出的要求。

延伸01

1. Automatically run cleanup on file save

「Automatically run cleanup on file save」:位於Cleaning->General設定頁面。當該選項設定為勾選時,會在檔案存檔的同時,自動執行程式碼排版功能。

延伸02

2. Run remove unused using statements

「Run remove unused using statements」:位於Cleaning->Visual Studio設定頁面。當該選項設定為勾選時,會在執行程式碼排版功能時,移除沒有使用的using定義。(開發階段建議不要勾選該選項,因為移除未使用的using定義,會造成使用LINQ時找不到擴充方法的問題。)

延伸03

3. Remove multple consecutive blank lines

「Remove multple consecutive blank lines」:位於Cleaning->Remove設定頁面。當該選項設定為勾選時,會在執行程式碼排版功能時,移除連續多行的空白行。

延伸06

4. Update #endregion tag with region name

「Update #endregion tag with region name」:位於Cleaning->Updae設定頁面。當該選項設定為勾選時,會在執行程式碼排版功能時,為#endregion區域標籤加上區域名稱。

延伸04

5. Alphabetize members of the same group

「Alphabetize members of the same group」:位於Reorganizing->General設定頁面。當該選項設定為勾選時,會在執行程式碼排版功能時,依照成員類型排序之後,增加依照字母順序排序的工作項目。

延伸05

參考資料

期許自己
能以更簡潔的文字與程式碼,傳達出程式設計背後的精神。
真正做到「以形寫神」的境界。