default branch is unnecessary

default branch is unnecessary

default branch is unnecessary

default branch is unnecessary

這個警告是在提醒你 switch 語句中的 default 分支是不必要的。
什麼情況下會出現這個警告?

  1. 枚舉 (Enum) 已涵蓋所有情況
    enum Color {
    RED, GREEN, BLUE
    }

// 不必要的 default
switch (color) {
case RED:
// 處理紅色
break;
case GREEN:
// 處理綠色
break;
case BLUE:
// 處理藍色
break;
default: // ← 這裡不必要!
throw new IllegalArgumentException();
}
2. 布林值的完整覆蓋
// 不必要的 default
switch (booleanValue) {
case true:
// 處理 true
break;
case false:
// 處理 false
break;
default: // ← 不會執行到這裡
break;
}
3. 有限範圍的數值已完全涵蓋
// 如果 dayOfWeek 只能是 1-7
switch (dayOfWeek) {
case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 處理所有可能值
break;
default: // ← 可能不必要
break;
}
為什麼要避免不必要的 default?

  1. 程式碼清晰度
    // 清楚表達:我們處理了所有可能的枚舉值
    switch (status) {
    case PENDING -> handlePending();
    case APPROVED -> handleApproved();
    case REJECTED -> handleRejected();
    // 沒有 default,表示我們確實涵蓋了所有情況
    }
  2. 編譯器幫助檢查
    enum Status {
    PENDING, APPROVED, REJECTED, CANCELLED // 新增了 CANCELLED
    }

// 編譯器會警告缺少 CANCELLED 的處理
switch (status) {
case PENDING -> handlePending();
case APPROVED -> handleApproved();
case REJECTED -> handleRejected();
// 編譯錯誤:缺少 CANCELLED 的處理
}
3. 避免隱藏錯誤
// 有 default 時,新增枚舉值可能被忽略
switch (status) {
case PENDING -> handlePending();
case APPROVED -> handleApproved();
case REJECTED -> handleRejected();
default -> { /* 默默忽略新的 CANCELLED 狀態 */ }
}
什麼時候需要保留 default?

  1. 處理未知值
    java// 處理用戶輸入或外部數據
    switch (userInput) {
    case 1 -> handleOption1();
    case 2 -> handleOption2();
    case 3 -> handleOption3();
    default -> showInvalidOptionError(); // 需要!
    }
  2. 未來擴展的預留
    switch (apiVersion) {
    case “v1” -> handleV1();
    case “v2” -> handleV2();
    default -> throw new UnsupportedVersionException(); // 合理
    }
    修正方式
    移除不必要的 default
    // 之前
    switch (color) {
    case RED -> handleRed();
    case GREEN -> handleGreen();
    case BLUE -> handleBlue();
    default -> throw new IllegalArgumentException(); // 移除這行
    }

// 之後
switch (color) {
case RED -> handleRed();
case GREEN -> handleGreen();
case BLUE -> handleBlue();
}
或者改用 if-else 邏輯
if (someCondition) {
// 處理
} else {
// 確實需要的預設處理
}
總之,這個警告是在幫助寫出更精確、更安全的程式碼!