一般來說,interfaces 是用來定義 class 的 Signature 的
當某個 class 實作了某個 interface,則該 interface 就變成了一種型別
可以用來指向這個 class 的實體
有一種interface,用來定義constant type
這種 interface 稱之為 constant interface
而 constant interface 其實是一種不良的 interface 運用
因為 「class 內部使用某些常數只是一種實作細節」
實現 constant interface 會導致實作細節洩漏至 class 的 exported API 中
如果一個 final class 實現了一個 constant interface,其所有的 subclasses 會因為 interface 中的常數而造成命名空間污染(namespaces pollution)
而常數若與既有的 class 或 interface 有緊密的關連,則應該將他們加入到那個 class 或 interface 中
這與 Refactoring 倒有些關連性
例如 Java 標準程式庫中的 Integer.MIX_VALUE 與 Integer.MAX_VALUE,都是類似的作法
而若該常數適合作為列舉型(enumerated type)成員,那你就應該以一個 typesafe enum class(條款21) 來匯出他們
否則應該以一個「不可被實體化」的 utility class(條款3) 加以匯出
總而言之,interface 應該只用來定義型別(types),而不應該用來匯出(export)常數.....
當某個 class 實作了某個 interface,則該 interface 就變成了一種型別
可以用來指向這個 class 的實體
有一種interface,用來定義constant type
這種 interface 稱之為 constant interface
public interface PEOPLE_Constant {
static final String MAN = "MALE";
static final String WOMAN = "FEMALE";
}
而 constant interface 其實是一種不良的 interface 運用
因為 「class 內部使用某些常數只是一種實作細節」
實現 constant interface 會導致實作細節洩漏至 class 的 exported API 中
如果一個 final class 實現了一個 constant interface,其所有的 subclasses 會因為 interface 中的常數而造成命名空間污染(namespaces pollution)
而常數若與既有的 class 或 interface 有緊密的關連,則應該將他們加入到那個 class 或 interface 中
這與 Refactoring 倒有些關連性
例如 Java 標準程式庫中的 Integer.MIX_VALUE 與 Integer.MAX_VALUE,都是類似的作法
而若該常數適合作為列舉型(enumerated type)成員,那你就應該以一個 typesafe enum class(條款21) 來匯出他們
否則應該以一個「不可被實體化」的 utility class(條款3) 加以匯出
public class PEOPLE_Constant {
prviate PEOPLE_Constant () {} // 不可被實體化
public static final String MAN = "MALE";
public static final String WOMAN = "FEMALE";
}
總而言之,interface 應該只用來定義型別(types),而不應該用來匯出(export)常數.....