良好的代碼風格始於工具自動化,而非人工對齊。
Window → Preferences → Java → Editor → Save Actions → 勾選 Perform the selected actions on save → 選中 Format source code + Organize imports
效果:每次 Ctrl+S 自動修復風格問題,團隊零爭議。
// ❌ 不推薦:多個返回點,難以調試與維護
public boolean isEligible(User user) {
if (user == null) return false;
if (user.getAge() < 18) return false;
if (!user.isActive()) return false;
return true;
}
// ✅ 推薦:單一出口,邏輯清晰
public boolean isEligible(User user) {
boolean eligible = false;
if (user != null && user.getAge() >= 18 && user.isActive()) {
eligible = true;
}
return eligible;
}
// ❌ 冗長
public String getStatus(boolean active) {
if (active) return "啟用";
else return "禁用";
}
// ✅ 三元運算符 / 表達式
public String getStatus(boolean active) {
return active ? "啟用" : "禁用";
}
// ❌ 創建新對象,性能差、內存壓力
Boolean b = new Boolean(true);
Integer i = new Integer(100);
String s = new String("hello");
// ✅ 靜態工廠方法,享受緩存與複用
Boolean b = Boolean.valueOf(true); // 返回 Boolean.TRUE/FALSE 單例
Integer i = Integer.valueOf(100); // -128~127 緩存
String s = "hello"; // 字面量直接引用常量池
// ❌ 極易導致維護時邏輯錯誤
if (condition)
doSomething();
doAnother(); // 視覺上屬於 if,實際無條件執行!
// ✅ 永遠加大括號,即使單行
if (condition) {
doSomething();
}
doAnother(); // 明確不屬於 if
// ✅ 推薦:參數聲明 final
public void process(final String input, final int maxRetry) {
// 編譯器保證不會意外修改參數引用
// 字節碼優化:final 參數可內聯常量傳遞
}
// ❌ 混淆視聽 public static final String apiUrl = "https://api.example.com"; private static final int maxCount = 100; // ✅ 全大寫 + 下劃線,一眼識別常量 public static final String API_URL = "https://api.example.com"; private static final int MAX_COUNT = 100;
// ❌ 重複判斷
if (user != null) {
if (user.isActive()) {
if (user.getAge() >= 18) { ... }
}
}
// ✅ 合併邏輯
if (user != null && user.isActive() && user.getAge() >= 18) { ... }
// ❌ 新增枚舉值時靜默失效
switch (status) {
case 1: return "啟用";
case 2: return "禁用";
}
// ✅ 防禦性編程
switch (status) {
case 1: return "啟用";
case 2: return "禁用";
default: throw new IllegalArgumentException("未知狀態:" + status);
}
// ❌ 分散維護風險
log.info("用戶登錄成功:{}", username);
audit.record("用戶登錄成功:{}", username);
notify.send("用戶登錄成功:{}", username);
// ✅ 提取常量
private static final String LOGIN_SUCCESS_MSG = "用戶登錄成功:{}";
log.info(LOGIN_SUCCESS_MSG, username);
audit.record(LOGIN_SUCCESS_MSG, username);
notify.send(LOGIN_SUCCESS_MSG, username);
Code → Reformat Code、Optimize Imports、Inspect Code代碼規範不是束縛,而是降低認知負荷、減少缺陷、提升協作效率的基礎設施。將格式化、靜態檢查納入 CI 流水線,讓機器守護質量,人類專注業務創新。