Alternative Classes with Different Interfaces

November 26, 20269 minutes

Email and text reminders do one job with two different method shapes, so every caller branches and the retry loop exists twice. Learn to line up the signatures, share a parent, and adapt what you can't change.

A clinic app sends appointment reminders. Patients can choose email or a text message, and both channels work fine. But look at the classes behind them. The email class has a method called sendMail, with an address and a body. The text class has dispatchText, with a phone, a message and an urgent flag. They do the same job, yet nothing about them looks alike. So every caller must check which one it holds, and each class retries failed sends with its own copy of the logic. That’s a smell called Alternative Classes with Different Interfaces: same job, different shapes.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

Two ways to say send

Here is the clinic app as a picture. One reminder goes to two classes, and each class speaks its own dialect.

A reminder card goes to two classes. EmailNotifier offers sendMail with an address and a body and has its own retry loop. SmsService offers dispatchText with a phone, a message and an urgent flag and has its own retry loop. Callers must branch on which class they hold. A reminder card goes to two classes. EmailNotifier offers sendMail with an address and a body and has its own retry loop. SmsService offers dispatchText with a phone, a message and an urgent flag and has its own retry loop. Callers must branch on which class they hold.
One job, two shapes.

Two remotes

Think of two remote controls for the same brand of television. Both turn the set on, change the channel, and set the volume. On the first remote, the volume buttons sit on the right. On the second, they sit at the bottom, and the power button has moved too.

Nothing is broken. But anyone who picks up the other remote has to relearn a job they already know. The callers in our clinic app are those people. They learn the email shape, then the text shape, though the job is one job: tell the patient. A better pair of remotes would put the same buttons in the same places.

What it looks like

Let us look at the two classes. The email class tries to deliver up to three times, and stops at the first success. The text class does the same thing with different names. It takes a phone and a message, and tries twice, or five times when the message is urgent.

class EmailNotifier {
    void sendMail(String address, String body) {
        for (int i = 0; i < 3; i++) {
            if (MailClient.deliver(address, body)) {
                return;
            }
        }
    }
}

class SmsService {
    void dispatchText(String phone, String msg, boolean urgent) {
        int tries = urgent ? 5 : 2;
        for (int i = 0; i < tries; i++) {
            if (SmsGateway.push(phone, msg)) {
                return;
            }
        }
    }
}

(MailClient and SmsGateway are placeholders for a mail library and a text gateway, not real APIs.)

And here’s a caller. It receives one of the two, checks which, and calls whichever method that class happens to have.

void remind(Appointment a, Object channel) {
    String text = "Visit on " + a.date();
    if (channel instanceof EmailNotifier e) {
        e.sendMail(a.email(), text);
    } else if (channel instanceof SmsService s) {
        s.dispatchText(a.phone(), text, false);
    }
}

Honestly, nobody was careless. The email class came first, the text class came later, and each was written to fit its own library.

Why it hurts

Now the clinic wants reminders by push notification. That means a third class, with a third set of names. Every caller that sends a reminder must learn a third branch, and the same check is repeated in each of them: reminders, billing, recalls.

Then comes the real cost. A bug in the retry loop, say a missing pause between tries, has to be found and fixed in each class separately. Search for one method name, and you find only one of the copies; the other hides behind a different name. And new developers can’t guess the shape. They must read both classes before they write a single line.

How to spot it

  • Callers branch on which class they hold, just to do one job.
  • One sentence describes both classes: “sends a message to a patient”.
  • The method bodies rhyme. The same loop, the same return on success. Only the library call differs.
  • Built twice, by two people. The Code Smells Reference names the usual cause: two developers build the same kind of thing without knowing the other already exists.

None of these alone proves it. Two or three together mean it’s time to look closer. The course page also lists similar hierarchies that do similar work, and classes that duplicate functionality that exists elsewhere in the code, as places to look.

The key insight: same job, same shape

Classes that do the same job should look the same to the code that calls them. The caller shouldn’t need to know whether a reminder goes by email or by text. It should just say send.

The insides can differ. Email may call a mail server, and the text class a gateway. Only the outside has to match. A good test for any pair: could the caller treat one as the other without noticing?

Same job, same shape.

The fix: line up the signatures

Start by lining up the signatures, one small step at a time. The course page calls the first step Rename Method; Fowler’s catalog files it under Change Function Declaration (Rename Method is one of its aliases). Both methods become send, so the names match.

Next, make the parameters match: add a parameter, or bundle several into one (refactoring.guru lists Add Parameter and Move Method for this step). A recipient holds the address and the phone, and a message holds the text and the urgent flag.

record Recipient(String email, String phone) {}
record Message(String text, boolean urgent) {}

class EmailNotifier {
    void send(Recipient to, Message msg) {
        for (int i = 0; i < 3; i++) {
            if (MailClient.deliver(to.email(), msg.text())) {
                return;
            }
        }
    }
}

class SmsService {
    void send(Recipient to, Message msg) {
        int tries = msg.urgent() ? 5 : 2;
        for (int i = 0; i < tries; i++) {
            if (SmsGateway.push(to.phone(), msg.text())) {
                return;
            }
        }
    }
}

The email class now accepts an urgent flag that it ignores. That’s fine: the flag belongs to the shape, even when one channel has no use for it. Do it in small steps and run your tests after each one. After each rename, let your editor update every caller, so the old name disappears everywhere in one safe move.

Extract Superclass (or Extract Interface)

Now the two classes look alike, but the retry loop is still written twice. Extract Superclass fixes that. Give both a parent called Notifier. The parent owns send and the one retry loop. The step that differs, a single attempt, stays abstract.

abstract class Notifier {
    void send(Recipient to, Message msg) {
        for (int i = 0; i < tries(msg); i++) {
            if (attempt(to, msg)) {
                return;
            }
        }
    }

    int tries(Message msg) {
        return 3;
    }

    abstract boolean attempt(Recipient to, Message msg);
}

Each child supplies only what is special. Email makes one delivery attempt. The text class (renamed SmsNotifier to match) does the same with its gateway, and also chooses how many tries.

class EmailNotifier extends Notifier {
    boolean attempt(Recipient to, Message msg) {
        return MailClient.deliver(to.email(), msg.text());
    }
}

class SmsNotifier extends Notifier {
    int tries(Message msg) {
        return msg.urgent() ? 5 : 2;
    }

    boolean attempt(Recipient to, Message msg) {
        return SmsGateway.push(to.phone(), msg.text());
    }
}

Now look at the caller. The branching is gone. It takes a notifier, and calls send.

void remind(Appointment a, Notifier channel) {
    Recipient to = new Recipient(a.email(), a.phone());
    Message msg = new Message("Visit on " + a.date(), false);
    channel.send(to, msg);
}

A new channel is one new subclass, and no caller changes. And a fix to the retry loop happens once.

If the classes share only a shape and no code, extract an interface instead: the same promise, without a parent class. (Extract Interface is a first-edition refactoring; refactoring.guru describes it as isolating only the shared interface, not shared code.)

interface Notifier {
    void send(Recipient to, Message msg);
}
Class diagram after Extract Superclass. Notifier declares send, tries and attempt. EmailNotifier, SmsNotifier and PagerAdapter all extend Notifier. PagerAdapter wraps the third-party PagerSdk. The remind caller uses a Notifier. Class diagram after Extract Superclass. Notifier declares send, tries and attempt. EmailNotifier, SmsNotifier and PagerAdapter all extend Notifier. PagerAdapter wraps the third-party PagerSdk. The remind caller uses a Notifier.
One shape, three channels.
Before and after Extract Superclass. Before, the caller branches on the type and reaches EmailNotifier.sendMail or SmsService.dispatchText, each with its own retry loop. After, the caller calls Notifier.send, and the one retry loop lives in Notifier. Before and after Extract Superclass. Before, the caller branches on the type and reaches EmailNotifier.sendMail or SmsService.dispatchText, each with its own retry loop. After, the caller calls Notifier.send, and the one retry loop lives in Notifier.
Before and after.

When you can’t change a class: Adapter

But what if one class isn’t yours? Say the clinic buys a pager library, and its page method takes a phone and a text. You can’t rename a method in someone else’s library, and you shouldn’t copy their code just to edit it.

Instead, write a small class of your own that wraps it. It extends Notifier and turns an attempt into the library’s call. That’s the Adapter pattern.

class PagerAdapter extends Notifier {
    private final PagerSdk sdk;

    PagerAdapter(PagerSdk sdk) {
        this.sdk = sdk;
    }

    boolean attempt(Recipient to, Message msg) {
        return sdk.page(to.phone(), msg.text());
    }
}

(PagerSdk is a placeholder for a third-party library, not a real API.)

The callers see one shape again, and the library stays untouched. When the library changes, only the adapter does.

A few neighbours. Two copies of the same retry loop are Duplicate Code. Here they hid behind different names, so nobody noticed. And a caller that branches on the type is close to Switch Statements. Once the classes share a parent, that branch becomes one plain call.

The signal is different, though. Duplicate Code is about repeated lines. This smell is about repeated jobs in different shapes, which is why a text search misses it.

Myths, and when to leave it

“Same method names mean the same behaviour.” They don’t. A draft store’s save overwrites silently. A booking store’s save rejects a double booking. Same name, different jobs. So line up interfaces only when the job is really the same. Forcing different jobs behind one name hides the differences that matter.

So when should you leave it?

  • When the classes live in separate contexts, owned by teams that deliberately keep their own vocabulary.
  • When one of them belongs to a library you don’t own. The Code Smells Reference says to ignore the smell when the classes live in different programs, libraries or frameworks. An adapter is the gentle option.

And if you’re unsure, wait. A smell is a prompt to look closer, not an order.

Decision flow. Do two classes do the same job? If no, leave them. If yes, can you change both? If no, write an Adapter. If yes, do they share code? If yes, Extract Superclass; if only a shape, Extract Interface. Line up the signatures with Rename Method first. Decision flow. Do two classes do the same job? If no, leave them. If yes, can you change both? If no, write an Adapter. If yes, do they share code? If yes, Extract Superclass; if only a shape, Extract Interface. Line up the signatures with Rename Method first.
When to align.

Recap

Alternative classes with different interfaces means two classes do one job in different shapes. Line up the signatures with Rename Method. Then pull the shared code up with Extract Superclass, or extract an interface. If you can’t change a class, wrap it in an Adapter. And merge only when the job is really the same.

Recap chain: two shapes for one job, Rename Method, then Extract Superclass or Interface. Recap chain: two shapes for one job, Rename Method, then Extract Superclass or Interface.
Same job, same shape.

Checklist:

  • Do two classes do the same job under different method names or parameter lists?
  • Do callers branch on which class they hold?
  • Is the same loop or the same logic written in both?
  • Can you change both classes? If not, wrap one in an Adapter.
  • Is the job really the same? If not, leave them apart.

Same job, same shape.

Further reading