整理 Effective Java 書中 Item 23: Prefer class hierarchies to tagged classes 心得筆記

主旨

在寫Java時,有時我們會想設計一個類別,可以代表「好幾種不同型態的物件」。這時,有些人會選擇用一個「tag 欄位」來做判斷,稱為 tagged class。但這樣的寫法其實有很多問題,本條目會說明為什麼應該用「類別階層」來取代「tagged class」。

🧨 什麼是 Tagged Class?

來看一個實際範例:

// 不推薦的 tagged class 寫法
class Notification {
    enum Type { EMAIL, SMS }

    final Type type;
    String emailAddress;
    String phoneNumber;
    String message;

    Notification(String emailAddress, String message) {
        this.type = Type.EMAIL;
        this.emailAddress = emailAddress;
        this.message = message;
    }

    Notification(String phoneNumber, String message, boolean isSMS) {
        this.type = Type.SMS;
        this.phoneNumber = phoneNumber;
        this.message = message;
    }

    void send() {
        switch (type) {
            case EMAIL:
                System.out.println("Sending EMAIL to " + emailAddress + ": " + message);
                break;
            case SMS:
                System.out.println("Sending SMS to " + phoneNumber + ": " + message);
                break;
        }
    }
}