Patterncore
Alternative Classes with Different Interfaces
Also called alternative classes.
A code smell: two classes do the same job but have different method names and parameters, so a client cannot swap one for the other and must know which one it has.
- Family
- code-smell
- Intent
- Find the classes that do one job under two interfaces, and change their declarations until they match, so that a client can use either one.
- Refactorings
- Change function declaration, Move function, Extract superclass
Intent
Find two classes that do the same job in different words: one has send(to, subject, body), the other has dispatch({ phone, text }). Rename the methods and reshape the parameters until the two classes have the same interface. Then a client can take either one, and the code that chooses between them is in one place.
Problem
Much of the value of classes comes from substitution. A client that asks an object to do a job should not need to know which class does it. That works only when the classes answer the same messages.
Refactoring makes this point: one of the great benefits of using classes is that one can be substituted for another, and that benefit is lost when two classes for the same job have different interfaces.1 The two classes often come from different authors or different times. One was written for email, the other was added for text messages a year later, and nobody aligned them.
The forces are these:
- Each class was designed alone, and its names fit its own case.
subjectmakes sense for email and not for a text message. - The clients must branch on the class. The branch is repeated wherever both classes are used, which is close to Repeated Switches.
- The two classes often share code under different names, which is Duplicated Code that a search does not find.
- A class that the team cannot change, such as one from a library, cannot be renamed. It needs a wrapper.
Solution
Refactoring gives the moves.1 The catalogue at refactoring.com has a card for each refactoring, and lists Rename Function as one of the names of Change Function Declaration.2
- Align the names and the parameters: Change Function Declaration. Pick one name for the job and one shape for the arguments, and change each class to match.
- Move the behaviour into place: Move Function. If one class does part of the job in its clients, move that part into the class, until the two classes do the same amount of work.
- Share what is the same: Extract Superclass, if the aligned classes now hold duplicated code.
The first edition gives the same advice, with Rename Method and Move Method as the names of the first two refactorings.3
When a class cannot be changed, the fix is a wrapper with the common interface. Wikipedia describes the adapter pattern as one that "allows the interface of an existing class to be used as another interface", and notes that it is used "to make existing classes work with others without modifying their source code."4
Example
An email sender and a text message gateway both deliver a message to a person. Their methods have different names and different arguments, so the function that alerts a user must check which one it has.
import assert from "node:assert/strict";
// Before: two classes for one job, with two interfaces.
class EmailSenderBefore {
constructor() { this.sent = []; }
send(to, subject, body) { this.sent.push(`email to ${to}: ${subject} | ${body}`); }
}
class SmsGatewayBefore {
constructor() { this.sent = []; }
dispatch({ phone, text }) { this.sent.push(`sms to ${phone}: ${text.slice(0, 40)}`); }
}
function alertBefore(channel, user, message) {
if (channel instanceof EmailSenderBefore) channel.send(user.email, "Alert", message);
else channel.dispatch({ phone: user.phone, text: message });
}
// After: one interface, deliver(user, message), in both classes.
class EmailSender {
constructor() { this.sent = []; }
deliver(user, message) { this.sent.push(`email to ${user.email}: Alert | ${message}`); }
}
class SmsGateway {
constructor() { this.sent = []; }
deliver(user, message) { this.sent.push(`sms to ${user.phone}: ${message.slice(0, 40)}`); }
}
const alert = (channel, user, message) => channel.deliver(user, message);
const ana = { email: "ana@example.org", phone: "+31600000000" };
const msg = "Your backup finished with 2 warnings.";
const pairs = [[new EmailSenderBefore(), new EmailSender()], [new SmsGatewayBefore(), new SmsGateway()]];
for (const [old, now] of pairs) {
alertBefore(old, ana, msg);
alert(now, ana, msg);
assert.deepEqual(now.sent, old.sent);
}
console.log("deliver: tests pass");
deliver: tests pass
In the second version alert has no branch. A third channel, such as a chat bot, needs only a deliver method, and no client changes.
| Language | What the example shows |
|---|---|
| JavaScript | two classes aligned to deliver(user, message), as above |
| Python | the same alignment, with a Protocol that names the interface |
| Java | the same alignment, with an interface that both classes implement |
| Go | the same alignment, with an interface that both types satisfy without declaring it |
from typing import Protocol
# Before: two classes for one job, with two interfaces.
class EmailSenderBefore:
def __init__(self):
self.sent = []
def send(self, to, subject, body):
self.sent.append(f"email to {to}: {subject} | {body}")
class SmsGatewayBefore:
def __init__(self):
self.sent = []
def dispatch(self, message):
self.sent.append(f"sms to {message['phone']}: {message['text'][:40]}")
def alert_before(channel, user, text):
if isinstance(channel, EmailSenderBefore):
channel.send(user["email"], "Alert", text)
else:
channel.dispatch({"phone": user["phone"], "text": text})
# After: one interface, deliver(user, text), in both classes.
class Channel(Protocol):
def deliver(self, user: dict, text: str) -> None: ...
class EmailSender:
def __init__(self):
self.sent = []
def deliver(self, user, text):
self.sent.append(f"email to {user['email']}: Alert | {text}")
class SmsGateway:
def __init__(self):
self.sent = []
def deliver(self, user, text):
self.sent.append(f"sms to {user['phone']}: {text[:40]}")
def alert(channel: Channel, user, text):
channel.deliver(user, text)
ana = {"email": "ana@example.org", "phone": "+31600000000"}
msg = "Your backup finished with 2 warnings."
for old, now in [(EmailSenderBefore(), EmailSender()), (SmsGatewayBefore(), SmsGateway())]:
alert_before(old, ana, msg)
alert(now, ana, msg)
assert now.sent == old.sent
print("deliver: tests pass")
deliver: tests pass
Channelis atyping.Protocol. Neither class names it, but a type checker such as mypy accepts both as aChannel, because both have a matchingdelivermethod. At run time Python does not check it.isinstanceinalert_beforeis the sign of the smell: the client must know the concrete class to call it.
import java.util.ArrayList;
import java.util.List;
public class Main {
record User(String email, String phone) {}
// Before: two classes for one job, with two interfaces.
static final class EmailSenderBefore {
final List<String> sent = new ArrayList<>();
void send(String to, String subject, String body) { sent.add("email to " + to + ": " + subject + " | " + body); }
}
static final class SmsGatewayBefore {
final List<String> sent = new ArrayList<>();
void dispatch(String phone, String text) {
sent.add("sms to " + phone + ": " + text.substring(0, Math.min(40, text.length())));
}
}
static void alertBefore(Object channel, User user, String text) {
if (channel instanceof EmailSenderBefore e) e.send(user.email(), "Alert", text);
else if (channel instanceof SmsGatewayBefore s) s.dispatch(user.phone(), text);
else throw new IllegalArgumentException("unknown channel");
}
// After: one interface, deliver(user, text), in both classes.
interface Channel {
void deliver(User user, String text);
}
static final class EmailSender implements Channel {
final List<String> sent = new ArrayList<>();
public void deliver(User user, String text) { sent.add("email to " + user.email() + ": Alert | " + text); }
}
static final class SmsGateway implements Channel {
final List<String> sent = new ArrayList<>();
public void deliver(User user, String text) {
sent.add("sms to " + user.phone() + ": " + text.substring(0, Math.min(40, text.length())));
}
}
static void alert(Channel channel, User user, String text) { channel.deliver(user, text); }
public static void main(String[] args) {
User ana = new User("ana@example.org", "+31600000000");
String msg = "Your backup finished with 2 warnings.";
EmailSenderBefore e0 = new EmailSenderBefore();
SmsGatewayBefore s0 = new SmsGatewayBefore();
EmailSender e1 = new EmailSender();
SmsGateway s1 = new SmsGateway();
alertBefore(e0, ana, msg);
alertBefore(s0, ana, msg);
for (Channel c : List.<Channel>of(e1, s1)) alert(c, ana, msg);
if (!e1.sent.equals(e0.sent) || !s1.sent.equals(s0.sent)) throw new AssertionError("sent");
System.out.println("deliver: tests pass");
}
}
deliver: tests pass
alertBeforetakes anObject, because the two classes have no common type. The compiler cannot stop a caller from passing something else, so the method needs a third branch that throws.Channelnames the common interface, andalerttakes aChannel. A wrong argument is now a compile error.
package main
import (
"fmt"
"slices"
)
type user struct{ email, phone string }
func first(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
// Before: two types for one job, with two method sets.
type emailSenderBefore struct{ sent []string }
func (e *emailSenderBefore) send(to, subject, body string) {
e.sent = append(e.sent, "email to "+to+": "+subject+" | "+body)
}
type smsGatewayBefore struct{ sent []string }
func (s *smsGatewayBefore) dispatch(phone, text string) {
s.sent = append(s.sent, "sms to "+phone+": "+first(text, 40))
}
func alertBefore(channel any, u user, text string) {
switch c := channel.(type) {
case *emailSenderBefore:
c.send(u.email, "Alert", text)
case *smsGatewayBefore:
c.dispatch(u.phone, text)
default:
panic("unknown channel")
}
}
// After: one interface. Both types satisfy it because they have the method.
type channel interface{ deliver(u user, text string) }
type emailSender struct{ sent []string }
func (e *emailSender) deliver(u user, text string) {
e.sent = append(e.sent, "email to "+u.email+": Alert | "+text)
}
type smsGateway struct{ sent []string }
func (s *smsGateway) deliver(u user, text string) {
s.sent = append(s.sent, "sms to "+u.phone+": "+first(text, 40))
}
func alert(c channel, u user, text string) { c.deliver(u, text) }
func main() {
ana := user{"ana@example.org", "+31600000000"}
msg := "Your backup finished with 2 warnings."
e0, s0 := &emailSenderBefore{}, &smsGatewayBefore{}
e1, s1 := &emailSender{}, &smsGateway{}
alertBefore(e0, ana, msg)
alertBefore(s0, ana, msg)
for _, c := range []channel{e1, s1} {
alert(c, ana, msg)
}
if !slices.Equal(e1.sent, e0.sent) || !slices.Equal(s1.sent, s0.sent) {
panic("sent")
}
fmt.Println("deliver: tests pass")
}
deliver: tests pass
- Go interfaces are satisfied implicitly. Once both types have a
delivermethod with the same signature, both are achannel, and neither type needs to mention it. - The type switch in
alertBeforeis the Go form of the branch on the class. The aligned interface removes it. firstcuts by bytes, which is correct here because the text is ASCII. Text with other characters needs a cut by runes.
Consequences
The clients depend on one interface. They can take either class, and a test can pass a fake that has the same method. The code that chooses a class moves to one place, such as the code that reads the user's settings.
The work can be larger than it looks. Each caller of the old methods must change, and if the classes are part of a published interface, the old names need a deprecation period. An adapter avoids that cost and keeps both names, at the price of one more class for each wrapped one.
Two classes that look alike may not be alternatives. If they do different jobs that happen to share a word, forcing one interface on them makes a client think it can swap them when it cannot. The test is whether a client could use either one and be correct.
How to fix it
- Methods with different names for one job: Change Function Declaration to rename them.1
- Methods with different parameters for one job: Change Function Declaration to reshape them.1
- One class that leaves part of the job to its clients: Move Function into the class.1
- Aligned classes with duplicated code: Extract Superclass.1
- A class that cannot be changed: an adapter. See Adapter pattern.4
Variants and related patterns
Interfaces. A language feature that names the common interface and lets the compiler check it. See Interfaces.
Adapter pattern. The fix when one of the classes cannot be edited. See Adapter pattern.
Repeated Switches. The branch on the class in each client is a switch that the aligned interface removes. See Repeated Switches.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Alternative Classes with Different Interfaces
- Martin Fowler, Catalog of Refactorings, the cards Change Function Declaration (alias Rename Function), Move Function and Extract Superclass
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Alternative Classes with Different Interfaces
- Wikipedia, Adapter pattern, revision 1340717395, the introduction and Overview
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag QJW6R9 Edit this page History Report an error Markdown