コンテンツにスキップ

開放閉鎖原則(OCP)を「変更箇所の局所化」として理解する

OCP の定義と実務的な捉え方

OCP(Open-Closed Principle):

「機能追加時に既存コードを変更せず、新コードの追加だけで済むようにする」

ただし「すべての変更を不要にする」のではなく、

「変更が避けられない箇所(対応付け)を 一点に局所化する」が実務的な本質。

Before: 条件分岐による実装(OCP 違反)

def send_notification(channel: str, message: str):
    if channel == "email":
        send_email(message)
    elif channel == "sms":
        send_sms(message)
    # 新チャネルを追加するたびここを変更 → OCP 違反

After: インターフェースと多態性(OCP 準拠)

class NotificationChannel(ABC):
    @abstractmethod
    def send(self, message: str) -> None: ...

class EmailChannel(NotificationChannel):
    def send(self, message: str) -> None:
        send_email(message)

class SmsChannel(NotificationChannel):
    def send(self, message: str) -> None:
        send_sms(message)

# 新チャネル追加: PushNotificationChannel を追加するだけ
# 既存コードへの変更ゼロ

# 対応付け(一箇所に局所化)
CHANNELS: dict[str, NotificationChannel] = {
    "email": EmailChannel(),
    "sms": SmsChannel(),
}

def send_notification(channel: str, message: str):
    CHANNELS[channel].send(message)

変更箇所の局所化

(図: SVG)