# Alternative Classes with Different InterfacesEmail 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.

{{< lesson-video youtube="sloPlh-2H8U" title="Alternative Classes with Different Interfaces" >}}

## 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.

```mermaid {alt="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." caption="One job, two shapes."}
flowchart LR
  R["Visit on Monday<br/>reminder"] --> E["EmailNotifier<br/>sendMail(address, body)"]
  R --> S["SmsService<br/>dispatchText(phone, msg, urgent)"]
  E --> RE["retry loop"]
  S --> RS["retry loop"]
  class E c5
  class S c4
  class RE,RS bad
```

## 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.

```java
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.

```java
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.

```java
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.

```java
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.

```java
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`.

```java
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.)

```java
interface Notifier {
    void send(Recipient to, Message msg);
}
```

```mermaid {alt="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." caption="One shape, three channels."}
classDiagram
  direction TB
  class Notifier {
    send(Recipient, Message)
    tries(Message)
    attempt(Recipient, Message)*
  }
  class EmailNotifier
  class SmsNotifier
  class PagerAdapter
  class PagerSdk
  Notifier <|-- EmailNotifier
  Notifier <|-- SmsNotifier
  Notifier <|-- PagerAdapter
  PagerAdapter o--> PagerSdk
```

```mermaid {alt="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." caption="Before and after."}
flowchart TB
  subgraph Before
    direction LR
    B1["caller<br/>if / else on the type"]
    B2["EmailNotifier<br/>own retry loop"]
    B3["SmsService<br/>own retry loop"]
    B1 --> B2
    B1 --> B3
  end
  subgraph After
    direction LR
    A1["caller<br/>send(to, msg)"] --> A2["Notifier<br/>one retry loop"]
    A2 --> A3["EmailNotifier"]
    A2 --> A4["SmsNotifier"]
  end
  Before ~~~ After
  class B1,B2,B3 bad
  class A2 good
```

## 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](/patterns/adapter-pattern/).

```java
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.

## Related smells

A few neighbours. Two copies of the same retry loop are [Duplicate Code](/code-smells/duplicate-code/). Here they hid behind
different names, so nobody noticed. And a caller that branches on the type is close to
[Switch Statements](/code-smells/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.

```mermaid {alt="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." caption="When to align."}
flowchart TD
  Q1{"same job<br/>for real?"} -->|no| L["leave them"]
  Q1 -->|yes| Q2{"can you change<br/>both classes?"}
  Q2 -->|no| AD["write an Adapter"]
  Q2 -->|yes| Q3{"do they share<br/>code?"}
  Q3 -->|yes| X1["Rename Method, then<br/>Extract Superclass"]
  Q3 -->|only a shape| X2["Rename Method, then<br/>Extract Interface"]
  class AD c6
  class X1,X2 good
  class L muted
```

## 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.

```mermaid {alt="Recap chain: two shapes for one job, Rename Method, then Extract Superclass or Interface." caption="Same job, same shape."}
flowchart LR
  A["two shapes,<br/>one job"] --> B["Rename<br/>Method"] --> C["Extract Superclass<br/>or Interface"]
  class C good
```

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

- Code Smells Reference: [Alternative Classes with Different Interfaces](https://refactoring-assistant.github.io/object-oriented-abusers/alternative-classes-with-different-interfaces).
- refactoring.guru: [Alternative Classes with Different Interfaces](https://refactoring.guru/smells/alternative-classes-with-different-interfaces).
- Refactoring catalog: [Change Function Declaration](https://refactoring.com/catalog/changeFunctionDeclaration.html),
  [Extract Superclass](https://refactoring.com/catalog/extractSuperclass.html),
  [Move Function](https://refactoring.com/catalog/moveFunction.html).
- refactoring.guru: [Extract Interface](https://refactoring.guru/extract-interface).
- On this site: [Adapter pattern](/patterns/adapter-pattern/), [Switch Statements](/code-smells/switch-statements/).
