Program to an Interface, Not a Class

When checkout asks for a card reader by name, every new way to pay means editing checkout; asking instead for "something that can take a payment", a promise any class can keep, lets a gift card, or anything else, plug in without checkout changing at all.

Apprentice · OOP · Software Development · Updated

By

After this lesson you can

  • Write code that asks for a promise (an interface) instead of one specific class
  • Spot code that depends on specific classes, and predict what a new kind will break

Key takeaways

  • Code that names specific classes (a card reader, a cash drawer) has to change whenever a new kind arrives.
  • Ask for what you need, not for who provides it: "something that can take a payment", not "a card reader".
  • The promise is an interface: in C#, Java and TypeScript an interface, in Python an abstract base class or Protocol, and in JavaScript any object with the right method.
  • Then a new kind is a new class that keeps the promise, and the code that uses it never changes.

Before this: Interfaces: A Promise Any Class Can Keep and Polymorphism: One Call, Many Behaviors.

The food truck takes cards and cash. Next month Rosa starts selling gift cards, and customers will want to pay with them at the window. The checkout code that's there today knows the card reader and the cash drawer by name, and asks each one in its own way. This lesson shows why that turns every new way to pay into an edit, and ends with the second idea behind the patterns: program to an interface, not a class.

The symptom: checkout knows every way to pay

Here's checkout as it is. A customer's order comes to $11, and checkout is told how they're paying:

Console.WriteLine(Checkout(11, "card"));
Console.WriteLine(Checkout(11, "cash"));
Console.WriteLine(Checkout(11, "gift card"));

// Checkout knows every way to pay by name, and how each one works.
string Checkout(int total, string method)
{
    if (method == "card")
    {
        CardReader reader = new CardReader();
        return reader.Charge(total);
    }
    else if (method == "cash")
    {
        CashDrawer drawer = new CashDrawer();
        return drawer.Take(total);
    }
    return "No way to pay";
}

class CardReader
{
    public string Charge(int amount) => quot;${amount} charged to the card";
}

class CashDrawer
{
    public string Take(int amount) => quot;${amount} paid in cash";
}
$11 charged to the card
$11 paid in cash
No way to pay
class CardReader {
    String charge(int amount) { return "quot; + amount + " charged to the card"; }
}

class CashDrawer {
    String take(int amount) { return "quot; + amount + " paid in cash"; }
}

// Checkout knows every way to pay by name, and how each one works.
String checkout(int total, String method) {
    if (method.equals("card")) {
        CardReader reader = new CardReader();
        return reader.charge(total);
    } else if (method.equals("cash")) {
        CashDrawer drawer = new CashDrawer();
        return drawer.take(total);
    }
    return "No way to pay";
}

void main() {
    IO.println(checkout(11, "card"));
    IO.println(checkout(11, "cash"));
    IO.println(checkout(11, "gift card"));
}
$11 charged to the card
$11 paid in cash
No way to pay
class CardReader:
    def charge(self, amount):
        return f"${amount} charged to the card"


class CashDrawer:
    def take(self, amount):
        return f"${amount} paid in cash"


def checkout(total, method):
    """Checkout knows every way to pay by name, and how each one works."""
    if method == "card":
        reader = CardReader()
        return reader.charge(total)
    elif method == "cash":
        drawer = CashDrawer()
        return drawer.take(total)
    return "No way to pay"


print(checkout(11, "card"))
print(checkout(11, "cash"))
print(checkout(11, "gift card"))
$11 charged to the card
$11 paid in cash
No way to pay
class CardReader {
  charge(amount) { return `${amount} charged to the card`; }
}

class CashDrawer {
  take(amount) { return `${amount} paid in cash`; }
}

// Checkout knows every way to pay by name, and how each one works.
function checkout(total, method) {
  if (method === "card") {
    const reader = new CardReader();
    return reader.charge(total);
  } else if (method === "cash") {
    const drawer = new CashDrawer();
    return drawer.take(total);
  }
  return "No way to pay";
}

console.log(checkout(11, "card"));
console.log(checkout(11, "cash"));
console.log(checkout(11, "gift card"));
$11 charged to the card
$11 paid in cash
No way to pay
class CardReader {
  charge(amount: number): string { return `${amount} charged to the card`; }
}

class CashDrawer {
  take(amount: number): string { return `${amount} paid in cash`; }
}

// Checkout knows every way to pay by name, and how each one works.
function checkout(total: number, method: string): string {
  if (method === "card") {
    const reader = new CardReader();
    return reader.charge(total);
  } else if (method === "cash") {
    const drawer = new CashDrawer();
    return drawer.take(total);
  }
  return "No way to pay";
}

console.log(checkout(11, "card"));
console.log(checkout(11, "cash"));
console.log(checkout(11, "gift card"));
$11 charged to the card
$11 paid in cash
No way to pay

The gift card customer can't pay. Nothing is wrong with the gift card; checkout has never heard of one.

  • The symptom: checkout has an if for each way to pay, makes each class itself with new, and calls each one by its own method name (Charge, Take).
  • The cause: checkout depends on specific classes, the card reader and the cash drawer, when all it needs from any of them is one thing: take this amount.

What would you try?

Add a third branch for the gift card. It works next month. The month after, Rosa adds tap-to-pay from a phone, and checkout is edited again. Checkout is the code that handles the money, and it's the code that changes most.

Give all three classes the same method name, Pay, and keep the if. That's a real step forward: now the branches look alike. But checkout still names each class and still needs a new branch for every new one.

Make the gift card a kind of card reader (a subclass). It isn't one. It would inherit the card reader's code for talking to a bank, which a gift card doesn't use, and checkout would still be stuck with the cash drawer's different shape.

The second try points the way. If every way to pay answered the same question the same way, checkout wouldn't need to know which one it had.

The idea: ask for the promise

A wall socket works this way. It doesn't know what you'll plug into it. A lamp, a toaster and a phone charger all fit, because each one has the plug the socket expects. The socket makes one promise ("any plug this shape gets power"), and anything that keeps its side of it works, including appliances that hadn't been invented when the house was built.

A wall socket with three different appliances lined up to plug into it, a lamp, a toaster and a phone charger, each with the same two-prong plug

In code, the promise is an interface: a list of methods a class promises to have, with no code of its own. Checkout asks for "something that can take a payment", an IPayment with one method, Pay. The card reader, the cash drawer and the new gift card each keep the promise in their own way, and checkout calls Pay on whatever it's handed. That's polymorphism doing its job: one call, a different behavior for each kind.

Checkout asks "take this amount" of something that can take a payment, the Payment promise, not of one class. CardReader, CashDrawer and GiftCard each keep the promise, inside a dashed fence labeled "what changes: the ways to pay"

List<IPayment> payments = new List<IPayment> { new CardReader(), new CashDrawer(), new GiftCard() };
foreach (IPayment payment in payments)
{
    Console.WriteLine(Checkout(11, payment));
}

// Checkout asks for the promise, not for any one class.
string Checkout(int total, IPayment payment) => payment.Pay(total);

// The promise: something that can take a payment.
interface IPayment
{
    string Pay(int amount);
}

class CardReader : IPayment
{
    public string Pay(int amount) => quot;${amount} charged to the card";
}

class CashDrawer : IPayment
{
    public string Pay(int amount) => quot;${amount} paid in cash";
}

class GiftCard : IPayment
{
    public string Pay(int amount) => quot;${amount} taken off the gift card";
}
$11 charged to the card
$11 paid in cash
$11 taken off the gift card
// The promise: something that can take a payment.
interface Payment {
    String pay(int amount);
}

class CardReader implements Payment {
    public String pay(int amount) { return "quot; + amount + " charged to the card"; }
}

class CashDrawer implements Payment {
    public String pay(int amount) { return "quot; + amount + " paid in cash"; }
}

class GiftCard implements Payment {
    public String pay(int amount) { return "quot; + amount + " taken off the gift card"; }
}

// Checkout asks for the promise, not for any one class.
String checkout(int total, Payment payment) {
    return payment.pay(total);
}

void main() {
    List<Payment> payments = List.of(new CardReader(), new CashDrawer(), new GiftCard());
    for (Payment payment : payments) {
        IO.println(checkout(11, payment));
    }
}
$11 charged to the card
$11 paid in cash
$11 taken off the gift card
from abc import ABC, abstractmethod


class Payment(ABC):
    """The promise: something that can take a payment."""

    @abstractmethod
    def pay(self, amount):
        ...


class CardReader(Payment):
    def pay(self, amount):
        return f"${amount} charged to the card"


class CashDrawer(Payment):
    def pay(self, amount):
        return f"${amount} paid in cash"


class GiftCard(Payment):
    def pay(self, amount):
        return f"${amount} taken off the gift card"


def checkout(total, payment):
    """Checkout asks for the promise, not for any one class."""
    return payment.pay(total)


for payment in [CardReader(), CashDrawer(), GiftCard()]:
    print(checkout(11, payment))
$11 charged to the card
$11 paid in cash
$11 taken off the gift card
// The promise, in words: anything with a pay(amount) method can take a payment.
class CardReader {
  pay(amount) { return `${amount} charged to the card`; }
}

class CashDrawer {
  pay(amount) { return `${amount} paid in cash`; }
}

class GiftCard {
  pay(amount) { return `${amount} taken off the gift card`; }
}

// Checkout asks for the promise, not for any one class.
function checkout(total, payment) {
  return payment.pay(total);
}

for (const payment of [new CardReader(), new CashDrawer(), new GiftCard()]) {
  console.log(checkout(11, payment));
}
$11 charged to the card
$11 paid in cash
$11 taken off the gift card
// The promise: something that can take a payment.
interface Payment {
  pay(amount: number): string;
}

class CardReader implements Payment {
  pay(amount: number): string { return `${amount} charged to the card`; }
}

class CashDrawer implements Payment {
  pay(amount: number): string { return `${amount} paid in cash`; }
}

class GiftCard implements Payment {
  pay(amount: number): string { return `${amount} taken off the gift card`; }
}

// Checkout asks for the promise, not for any one class.
function checkout(total: number, payment: Payment): string {
  return payment.pay(total);
}

const payments: Payment[] = [new CardReader(), new CashDrawer(), new GiftCard()];
for (const payment of payments) {
  console.log(checkout(11, payment));
}
$11 charged to the card
$11 paid in cash
$11 taken off the gift card

The gift card pays now, and checkout is one line that won't change again. Tap-to-pay next month is one new class that keeps the promise; checkout never hears its name. Notice also that checkout no longer says new for any of them: it's handed the payment. Who makes it is someone else's job, an idea that comes back in Dependency Inversion.

Try it. Add a PhonePay class that prints $11 paid by phone, and add it to the list. Don't touch checkout.

Where the languages differ. C# and Java write the promise with interface and a class keeps it with : or implements; C# names interfaces with an I in front, IPayment. TypeScript has interface too. Python has no interface keyword, so it uses an abstract base class (ABC), whose @abstractmethod marks what every kind must have. JavaScript has neither: any object with a pay method will do, which is called duck typing ("if it walks like a duck and quacks like a duck…"). The promise is still there; it's written in a comment instead of in the code.

How it got its name

This advice is on the first pages of the 1994 book that named the classic design patterns, worded as program to an interface, not an implementation. An implementation is a specific class that does the work, like the card reader. Interface there means the promise, whatever the language writes it with. Nearly every pattern in this course depends on it: a pattern lets you swap one piece for another, and that only works when the code using the piece asks for the promise, not the piece.

Where you've already used it

  • In Java, List<String> names = new ArrayList<>(); declares the variable as the promise (List) and picks the class (ArrayList) only once.
  • C#'s foreach and Python's and JavaScript's for loops work on anything that promises to hand out items one at a time: a list, a set, a dictionary's keys, a file's lines.
  • Python's len(x) works on anything that keeps the promise of having a length.

When not to use it

  • When there's only one kind and there will only be one. An interface for every class, in case it's ever needed, doubles the files and helps nobody. Add the promise when a second kind arrives, or when tests need a stand-in.
  • For plain data. A receipt line with a name and a price doesn't need an interface; it's plain data.

Check yourself

2 questions to try on the lesson page.

So what

Ask for what your code needs, not for who provides it today. When checkout asks for "something that can take a payment", the next way to pay is a new class, and the code that handles the money stays the same.

Key terms

Cheat sheets