[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

參考數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM