需判斷整數 n 是否滿足:32 < n < 48 且 n ≠ 36, 38, 45, 46, 47。若直接堆疊 if (n > 32 && n < 48 && n != 36 && n != 38 ...),程式碼冗長且難以維護。
int[] exclude = { 36, 38, 45, 46, 47 };
if (n > 32 && n < 48 && !exclude.Contains(n))
{
// 符合條件的處理邏輯
}
若專案中多處需用,可封裝為擴充方法:
public static class IntExtensions
{
public static bool InRangeExcept(this int value, int min, int max, params int[] except)
{
return value > min && value < max && !except.Contains(value);
}
}
// 呼叫端
if (n.InRangeExcept(32, 48, 36, 38, 45, 46, 47))
{
// ...
}
Contains 針對陣列為 O(N) 線性搜尋,排除值較少(< 20)時影響可忽略。HashSet<int>:static readonly HashSet<int> Exclude = new HashSet<int> {36,38,45,46,47};,查詢為 O(1)。switch 或位元遮罩,但通常不必要。| 語言 | 簡潔寫法 |
|---|---|
| Java | Set<Integer> ex = Set.of(36,38,45,46,47); if (n>32 && n<48 && !ex.contains(n)) |
| Python | exclude = {36,38,45,46,47}; if 32 < n < 48 and n not in exclude: |
| JavaScript | const exclude = new Set([36,38,45,46,47]); if (n>32 && n<48 && !exclude.has(n)) |
善用集合與擴充方法,讓條件判斷既清晰又易維護,是程式碼品質提升的關鍵一步。