[Intellij] Checkstyle and Code Style

Checkstyle

介紹

  1. 根據定義好的規則對程式碼進行檢查,以確保程式碼的 Style 是一致的 (盡力…)
  2. Checkstyle GitHub 有提供兩種規則範例,後續套用的規則即是使用 “Google Checks” 進行修改
    • Sun Checks
    • Google Checks

安裝 Checkstyle

  1. Preferences.. ➔ Plugins ➔ Browse repositories.. -> 搜尋 “CheckStyle”
  2. 安裝 “CheckStyle-IDEA”

Checkstyle 規則文件說明

  1. checkstyle/qmi_checks.xml 為 Checkstyle 主規則檔案
    • 定義檢查的檔案格式、範圍
    • 定義排除的規則檔案位置 (通常為 suppressions.xml)
    • 定義檢查的項目,每一個項目可定義的屬性不固定,需檢視 官方說明文件
  2. checkstyle/suppressions.xml 為 Checkstyle 的例外設定
    • 針對特定檢查規則定義排除檢查的檔案

套用 Checkstyle規則

  1. 選擇 Checkstyle version: 8.12 (至少8.11, 因有 LambdaParameterName 設定)
  2. Preferences.. ➔ Other Settings ➔ Checkstyle ➔ Add Configuration File
  3. 匯入後設定為 Active

啟用 Checkstyle 即時檢查

  1. Preferences.. ➔ Editor ➔ Inspections ➔ Checkstyle ➔ Checkstyle real-time scan
  2. 預設為開啟

產生 Checkstyle 檢查報告

  1. 下載檔案
  2. 產生XML格式報告
  3. 使用 Mac 內建程式 “xsltproc” 將 XML 報表轉成 HTML 格式

Code Style

介紹

  1. Intellij 編輯器內建功能,根據定義好的 Schema 進行檢查
  2. 官網介紹
  3. 可透過 “Save Actions” 設定當檔案儲存時自動執行 Reformat Code 及 Optimize Imports 以符合 Code Style 規則

匯入 Code Style 設定檔案

  1. 檔案位置: checkstyle/qmicodeformat.xml
  2. Preferences.. ➔ Editor ➔ Code Style ➔ Java ➔ Schema ➔ Import Schema ➔ IntelliJ IDEA code style XML

安裝 Save Actions

  1. Preferences.. ➔ Plugins ➔ Browse repositories.. -> 搜尋 “Save Actions”
  2. 安裝 “Save Actions”

設定 Save Actions

  1. Preferences.. ➔ Other Settings ➔ Save Action ➔ General ➔勾選 “Activate save actions on save (before saving each file, performs the configured actions below)”
  2. Preferences.. ➔ Other Settings ➔ Save Action ➔ General ➔勾選 “Optimize Imports”, “Reformat file”, “Rearrange fields and methods”

備註說明

  1. 因 Code Style 的 Arrangement 功能容易跟 Checkstyle 的規則抵觸,估會將 Arrangement 的功能關閉
  2. JavaDoc 中定義 Map 時,切勿使用 “Map<Object, Object>” 等形式編寫,此會造成 Code Style 誤判而對齊調整格式,導致每次儲存都會出現變動
This entry was posted in Intellij. Bookmark the permalink.