Site icon NexGismo

Polymorphism in OOP: Replace an if/elif Notification Chain

Polymorphism in OOP: Replace an if/elif Notification Chain

OOP in Practice · Episode 4 of 70 · OOP Foundations · Beginner · Python 3.13.18

The problem

You’re building order-update messages for an online shop, a classic place where polymorphism in OOP earns its keep. One function, send_notification(), picks the channel with an if/elif chain: email, SMS, push and now WhatsApp. Slack is next, which means editing the same function again.

Your task: redesign the sender so each channel is its own object and the sending code never asks which channel it is talking to.

Requirements

  • Send one message over any list of channels in one call.
  • Each channel has its own rules: email subject from the first sentence, SMS in 160-character segments, push trimmed to 40 characters, WhatsApp only after opt-in.
  • A user with no address for a channel is skipped with a reason, not crashed.
  • An unknown channel name or an empty message is rejected before anything is sent.
  • A new channel (Slack) is one new class, with no edits to existing code.
  • An object without a send() method cannot be registered as a channel.

Constraints and assumptions

  • Single process, in memory. “Sending” returns a delivery record instead of calling a real provider.
  • The 160 and 40 character limits are practice numbers, not any provider’s rules.
  • Python standard library only.

What this tests: polymorphism, duck typing, dynamic dispatch, typing.Protocol, replace conditional with polymorphism

Polymorphism in OOP means one call works on many types. Each channel class here has the same send(user, message) method, and NotificationService just calls it. Python picks the right version at run time. A typing.Protocol names that shape, so a new Slack channel plugs in without inheritance and without an if/elif chain.

Try it yourself first — hint

Every branch answers the same question: “how do I deliver this message to this user?” Make that question a method, and give each channel its own class that answers it.

Step 1: Identify the objects and responsibilities

Notification classes after the refactor
Class / interface Responsibility Key methods
Notifier (Protocol) The shape every channel must have. Nothing inherits from it. channel, send()
EmailNotifier, SmsNotifier, PushNotifier, WhatsAppNotifier One channel’s rules each: which address to use, limits, opt-in. send()
User (frozen dataclass) Contact details and the WhatsApp opt-in flag. —
Delivery (frozen dataclass) Immutable record of one attempt: sent or skipped, with a reason. __str__()
NotificationService Holds the registered notifiers, validates a request, calls send() on each. register(), notify()
SlackNotifier (demo) A channel added later without touching any code above it. send()

Step 2: The naive approach and why it breaks

def send_notification(user: dict, channel: str, message: str) -> str:
    if channel == "email":
        return f"email to {user['email']}: {message.split('.')[0]}"
    elif channel == "sms":
        return f"sms to {user['phone']}: {message}"
    elif channel == "push":
        return f"push to {user['device_token']}: {message[:40]}"
    elif channel == "whatsapp":
        return f"whatsapp to {user['phone']}: {message}"
    # anything else falls through and returns None


def max_length(channel: str) -> int:  # a second copy of the same chain
    if channel == "sms":
        return 160
    elif channel == "push":
        return 40
    return 10_000  # email, whatsapp... and any channel nobody remembered


ben = {"name": "Ben", "email": "ben@example.com"}
print(send_notification(ben, "email", "Your order #1042 has shipped."))
print(send_notification(ben, "Email", "Your order #1042 has shipped."))
print(max_length("slack"))
print(send_notification(ben, "sms", "Your order #1042 has shipped."))

Running it with python3 naive.py prints this (the traceback is cut to its last line):

email to ben@example.com: Your order #1042 has shipped
None
10000
KeyError: 'phone'

Step 3: The design

          +------------------------------+
          |     NotificationService      |
          |------------------------------|
          | register(notifier)           |
          | notify(user, msg, channels)  |
          +--------------+---------------+
                         | dict[str, Notifier]; calls send()
                         v
          +------------------------------+
          |    <<Protocol>> Notifier     |
          |------------------------------|
          | channel: str                 |
          | send(user, msg) -> Delivery  |
          +------------------------------+
             :       :       :       :       :     matched by shape
             :       :       :       :       :     (no base class)
        +-------+ +-----+ +------+ +----------+ +-------+
        | Email | | Sms | | Push | | WhatsApp | | Slack |
        +-------+ +-----+ +------+ +----------+ +-------+
             each send() returns a frozen Delivery
             (channel, to, status: sent | skipped, detail)

This is the Replace Conditional with Polymorphism refactoring. Each branch becomes a class with the same send() method. The service makes one call; the object decides what it does.

In the inheritance episode, the shared method came from an abstract base class. Python does not need one: duck typing calls the method without checking the object’s type, so SlackNotifier works with no parent class.

Duck typing alone documents nothing. A typing.Protocol writes the shape down so a type checker can verify it, and @runtime_checkable lets register() reject objects that lack it.

Step 4: The polymorphism in OOP solution in Python

"""Polymorphism in OOP: replace an if/elif notification chain (OOP in Practice, ep 4)."""
from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
from typing import Protocol, runtime_checkable


@dataclass(frozen=True)
class User:
    name: str
    email: str | None = None
    phone: str | None = None
    device_token: str | None = None
    whatsapp_opt_in: bool = False


@dataclass(frozen=True)
class Delivery:
    channel: str
    to: str
    status: str  # "sent" or "skipped"
    detail: str

    def __str__(self) -> str:
        return f"[{self.channel:<8}] {self.status:<7} {self.to:<17} {self.detail}"


@runtime_checkable
class Notifier(Protocol):
    """Anything with a channel name and a send() method is a notifier."""
    channel: str

    def send(self, user: User, message: str) -> Delivery: ...


def skipped(channel: str, why: str) -> Delivery:
    return Delivery(channel, "-", "skipped", why)


class EmailNotifier:
    channel = "email"

    def send(self, user: User, message: str) -> Delivery:
        if not user.email:
            return skipped(self.channel, "no email address")
        subject = message.split(".")[0]
        return Delivery(self.channel, user.email, "sent", f'subject="{subject}"')


class SmsNotifier:
    channel = "sms"
    SEGMENT = 160  # characters per SMS segment in this practice model

    def send(self, user: User, message: str) -> Delivery:
        if not user.phone:
            return skipped(self.channel, "no phone number")
        parts = -(-len(message) // self.SEGMENT)  # ceiling division
        return Delivery(self.channel, user.phone, "sent", f"{len(message)} chars, {parts} segment(s)")


class PushNotifier:
    channel = "push"
    MAX = 40

    def send(self, user: User, message: str) -> Delivery:
        if not user.device_token:
            return skipped(self.channel, "no device registered")
        body = message if len(message) <= self.MAX else message[: self.MAX - 3] + "..."
        return Delivery(self.channel, user.device_token, "sent", f'body="{body}"')


class WhatsAppNotifier:
    channel = "whatsapp"

    def send(self, user: User, message: str) -> Delivery:
        if not (user.phone and user.whatsapp_opt_in):
            return skipped(self.channel, "user has not opted in")
        return Delivery(self.channel, user.phone, "sent", "template=order_update")


class NotificationService:
    """Sends one message over the requested channels. Knows no channel by name."""

    def __init__(self) -> None:
        self._notifiers: dict[str, Notifier] = {}

    def register(self, notifier: object) -> None:
        if not isinstance(notifier, Notifier):
            raise TypeError(f"{type(notifier).__name__} has no channel/send(), so it is not a Notifier")
        if notifier.channel in self._notifiers:
            raise ValueError(f"channel '{notifier.channel}' is already registered")
        self._notifiers[notifier.channel] = notifier

    def notify(self, user: User, message: str, channels: list[str]) -> list[Delivery]:
        if not message.strip():
            raise ValueError("message is empty")
        unknown = [c for c in channels if c not in self._notifiers]
        if unknown:
            raise ValueError(f"unknown channel(s): {', '.join(unknown)}")
        # One call site, many behaviours: Python picks send() from each object's class.
        return [self._notifiers[c].send(user, message) for c in channels]


# ── demo ────────────────────────────────────────────────────────────────
class SlackNotifier:  # added later; inherits nothing, edits nothing above
    channel = "slack"

    def send(self, user: User, message: str) -> Delivery:
        return Delivery(self.channel, f"@{user.name.lower()}", "sent", "posted to DM")


class Printer:  # has no send(): must be rejected
    channel = "print"


if __name__ == "__main__":
    service = NotificationService()
    for n in (EmailNotifier(), SmsNotifier(), PushNotifier(), WhatsAppNotifier(), SlackNotifier()):
        service.register(n)

    msg = "Your order #1042 has shipped. It arrives on Friday."
    asha = User("Asha", "asha@example.com", "+91-90000-11111", "dev-7f3a", whatsapp_opt_in=True)
    ben = User("Ben", email="ben@example.com")

    print("Asha, all channels:")
    for d in service.notify(asha, msg, ["email", "sms", "push", "whatsapp", "slack"]):
        print(" ", d)
    print("Ben, email-only user:")
    for d in service.notify(ben, msg, ["email", "sms", "push", "whatsapp"]):
        print(" ", d)

    print("Edge cases:")
    cases: list[tuple[str, Callable[[], object]]] = [
        ("unknown channel", lambda: service.notify(ben, msg, ["fax"])),
        ("empty message", lambda: service.notify(ben, "   ", ["email"])),
        ("not a notifier", lambda: service.register(Printer())),
        ("duplicate", lambda: service.register(EmailNotifier())),
    ]
    for label, action in cases:
        try:
            action()
        except (ValueError, TypeError) as e:
            print(f"  {label:<16} -> {type(e).__name__}: {e}")

    long_sms = service.notify(asha, "x" * 161, ["sms"])[0]
    assert long_sms.detail == "161 chars, 2 segment(s)", long_sms
    assert isinstance(SlackNotifier(), Notifier) and not isinstance(Printer(), Notifier)
    print("  161-char SMS     ->", long_sms.detail)
    print("All checks passed.")

Step 5: Run it and check the output

Asha, all channels:
  [email   ] sent    asha@example.com  subject="Your order #1042 has shipped"
  [sms     ] sent    +91-90000-11111   51 chars, 1 segment(s)
  [push    ] sent    dev-7f3a          body="Your order #1042 has shipped. It arri..."
  [whatsapp] sent    +91-90000-11111   template=order_update
  [slack   ] sent    @asha             posted to DM
Ben, email-only user:
  [email   ] sent    ben@example.com   subject="Your order #1042 has shipped"
  [sms     ] skipped -                 no phone number
  [push    ] skipped -                 no device registered
  [whatsapp] skipped -                 user has not opted in
Edge cases:
  unknown channel  -> ValueError: unknown channel(s): fax
  empty message    -> ValueError: message is empty
  not a notifier   -> TypeError: Printer has no channel/send(), so it is not a Notifier
  duplicate        -> ValueError: channel 'email' is already registered
  161-char SMS     -> 161 chars, 2 segment(s)
All checks passed.

Tested: Python 3.13.18 — python3 main.py, 2026-11-17. Output above is copied from that run.

We also ran mypy --strict main.py (mypy 2.3.1): no issues. Passing a Printer where a Notifier is expected made mypy report the missing send member.

Why this design works

Trade-offs, edge cases and when not to use it

if/elif chain vs polymorphic classes
Criterion if/elif chain Polymorphic classes
Number of variants Two or three, rarely changing Many, or growing
Where the type test lives Copied into every function that cares Once, when the object is chosen
Adding a variant Edit every chain Add one class and register it
Reading the whole flow One screen Jump between classes
Unknown variant Silent fall-through unless you add an else Rejected at lookup

Polymorphism is overkill for a short, stable branch. Refactoring.Guru’s guidance on the switch smell is to leave a simple one alone, and it notes that factories commonly use a switch to choose which class to create. My recommendation: refactor when the same type test shows up in a second function.

Interview follow-up questions

Something still has to map “sms” to SmsNotifier. Where does that choice go?

To the edge of the program, once. Here startup code registers each notifier, and the registry maps a name to an object. In a bigger system a factory or config file does that mapping. One conditional in a factory is fine. The problem was the same test copied through business logic. notify() stays free of channel names.

How would you add retries or send to channels in parallel?

Keep the Notifier contract and wrap it. A RetryingNotifier holds another notifier and calls its send() up to N times. It has the same shape, so the service cannot tell the difference. For parallel sending, run each send() in a worker pool; these notifiers share no state. If one ever holds state, such as a connection, give it a lock.

How would you unit test this design?

Test each notifier alone: a full User gives sent; a user missing the field gives skipped with the right reason. Check boundaries, such as 160 and 161 SMS characters. Test the service with a small fake class that records calls. Duck typing means the fake needs no base class or mocking library. Assert that an unknown channel raises before any fake is called.

The same solution in TypeScript

Show the TypeScript version

TypeScript type compatibility is based on structural subtyping, so SlackNotifier needs no implements clause. A class missing send() fails to compile (we saw error TS2741).

// Polymorphism in OOP — TypeScript version (OOP in Practice, ep 4)
interface User {
  name: string;
  email?: string;
  phone?: string;
  deviceToken?: string;
  whatsappOptIn?: boolean;
}

interface Delivery { channel: string; to: string; status: "sent" | "skipped"; detail: string; }

interface Notifier {
  readonly channel: string;
  send(user: User, message: string): Delivery;
}

const skipped = (channel: string, why: string): Delivery => ({ channel, to: "-", status: "skipped", detail: why });

class EmailNotifier implements Notifier {
  readonly channel = "email";
  send(user: User, message: string): Delivery {
    if (!user.email) return skipped(this.channel, "no email address");
    return { channel: this.channel, to: user.email, status: "sent", detail: `subject="${message.split(".")[0]}"` };
  }
}

class SmsNotifier implements Notifier {
  readonly channel = "sms";
  send(user: User, message: string): Delivery {
    if (!user.phone) return skipped(this.channel, "no phone number");
    const parts = Math.ceil(message.length / 160);
    return { channel: this.channel, to: user.phone, status: "sent", detail: `${message.length} chars, ${parts} segment(s)` };
  }
}

class PushNotifier implements Notifier {
  readonly channel = "push";
  send(user: User, message: string): Delivery {
    if (!user.deviceToken) return skipped(this.channel, "no device registered");
    const body = message.length <= 40 ? message : message.slice(0, 37) + "...";
    return { channel: this.channel, to: user.deviceToken, status: "sent", detail: `body="${body}"` };
  }
}

class WhatsAppNotifier implements Notifier {
  readonly channel = "whatsapp";
  send(user: User, message: string): Delivery {
    if (!(user.phone && user.whatsappOptIn)) return skipped(this.channel, "user has not opted in");
    return { channel: this.channel, to: user.phone, status: "sent", detail: "template=order_update" };
  }
}

// No "implements": structural typing still accepts it as a Notifier.
class SlackNotifier {
  readonly channel = "slack";
  send(user: User, _message: string): Delivery {
    return { channel: this.channel, to: "@" + user.name.toLowerCase(), status: "sent", detail: "posted to DM" };
  }
}

class NotificationService {
  private readonly notifiers = new Map<string, Notifier>();

  register(n: Notifier): void {
    if (this.notifiers.has(n.channel)) throw new Error(`channel '${n.channel}' is already registered`);
    this.notifiers.set(n.channel, n);
  }

  notify(user: User, message: string, channels: string[]): Delivery[] {
    if (!message.trim()) throw new Error("message is empty");
    const unknown = channels.filter((c) => !this.notifiers.has(c));
    if (unknown.length) throw new Error(`unknown channel(s): ${unknown.join(", ")}`);
    return channels.map((c) => this.notifiers.get(c)!.send(user, message));
  }
}

const show = (d: Delivery): string =>
  `  [${d.channel.padEnd(8)}] ${d.status.padEnd(7)} ${d.to.padEnd(17)} ${d.detail}`;

const service = new NotificationService();
[new EmailNotifier(), new SmsNotifier(), new PushNotifier(), new WhatsAppNotifier(), new SlackNotifier()]
  .forEach((n) => service.register(n));

const msg = "Your order #1042 has shipped. It arrives on Friday.";
const asha: User = { name: "Asha", email: "asha@example.com", phone: "+91-90000-11111", deviceToken: "dev-7f3a", whatsappOptIn: true };
const ben: User = { name: "Ben", email: "ben@example.com" };

console.log("Asha, all channels:");
service.notify(asha, msg, ["email", "sms", "push", "whatsapp", "slack"]).forEach((d) => console.log(show(d)));
console.log("Ben, email-only user:");
service.notify(ben, msg, ["email", "sms", "push", "whatsapp"]).forEach((d) => console.log(show(d)));
try {
  service.notify(ben, msg, ["fax"]);
} catch (e) {
  console.log(`  unknown channel  -> ${(e as Error).message}`);
}
Asha, all channels:
  [email   ] sent    asha@example.com  subject="Your order #1042 has shipped"
  [sms     ] sent    +91-90000-11111   51 chars, 1 segment(s)
  [push    ] sent    dev-7f3a          body="Your order #1042 has shipped. It arri..."
  [whatsapp] sent    +91-90000-11111   template=order_update
  [slack   ] sent    @asha             posted to DM
Ben, email-only user:
  [email   ] sent    ben@example.com   subject="Your order #1042 has shipped"
  [sms     ] skipped -                 no phone number
  [push    ] skipped -                 no device registered
  [whatsapp] skipped -                 user has not opted in
  unknown channel  -> unknown channel(s): fax

Tested: TypeScript 7.0.2 with Node v22.23.4 — tsc --strict --target es2022 --module commonjs main.ts && node main.js, 2026-11-17.

Practice: extend it yourself

  1. Write a QuietHoursNotifier that wraps another notifier and takes the current hour in its constructor. Expected behaviour: wrapping SmsNotifier with hour 23 returns skipped with “quiet hours”; with hour 9 it returns the same delivery as a plain SmsNotifier. NotificationService is not edited.
  2. Write a FallbackNotifier(first, second) that tries first and uses second only if the first was skipped. Expected behaviour: for Ben (email only), FallbackNotifier(PushNotifier(), EmailNotifier()) returns sent to ben@example.com.
  3. Add asserts for the SMS segment boundaries. Expected behaviour: 160 characters gives “160 chars, 1 segment(s)”; 320 gives “320 chars, 2 segment(s)”.

Frequently Asked Questions

What is polymorphism in OOP in simple words?

Polymorphism in OOP means one call does the right thing for different kinds of objects. In this episode the service calls send() on any notifier, and the email, SMS or push class each runs its own version. The caller never checks the type. The object's class decides which code runs.

What are the types of polymorphism?

The common split is three forms. Ad hoc polymorphism is separate implementations behind one name, such as overloading. Parametric polymorphism is generic code written with type placeholders. Subtype polymorphism is code written for a supertype that also works for its subtypes. Java-focused tutorials often shorten this to compile-time (overloading) and run-time (overriding) polymorphism.

Can you have polymorphism without inheritance?

Yes. In Python, duck typing means any object with the right methods works, so SlackNotifier inherits nothing and still plugs in. TypeScript is structurally typed, so a class matches an interface by its members. Nominally typed languages such as Java need the class to declare the shared interface or base class.

Does Python support method overloading?

Not by signature. A second def with the same name simply replaces the first. The @typing.overload decorator only describes signatures to type checkers; at run time the one undecorated implementation is used. If you need behaviour chosen by the type of a function's first argument, functools.singledispatch does that.

References

Exit mobile version