Interfaces: A Promise Any Class Can Keep

When code is written for one class, every new kind of thing means a copy of that code; an interface writes down a promise (a name and a price for some hours) that any class can keep, so the code asks for the promise instead of the class, in C#, Java and TypeScript, with an abstract base class in Python and duck typing in JavaScript.

Apprentice · OOP · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Write an interface, and classes that keep its promise, so code can ask for anything that keeps it
  • Explain how each language checks a promise: an interface, Python's abstract base class or Protocol, and JavaScript's duck typing

Key takeaways

  • Code written for one class has to be copied for every new kind of thing, and the copies drift apart.
  • An interface is a written promise: the methods a class must have. A class that has them keeps the promise.
  • Code that asks for the promise, not the class, works with every class that keeps it, including ones written next year.
  • C#, Java and TypeScript have interfaces; Python uses an abstract base class or a Protocol; JavaScript trusts any object with the right methods.

Before this: Classes and Objects, which shows how to write a class with fields and methods.

Almost every pattern in this course rests on one move: code that asks for "anything that can do this job" instead of one particular class. That move has a name, an interface, and you'll use it in nearly every lesson from here on. Here's the problem it solves.

The desk's receipt, written for bikes

Pedal & Go rents bikes from a desk by the park, at $10 an hour. The desk prints a receipt line for each rental, and the code for it was written when bikes were all there was. Then e-bikes arrived, at $15 an hour, so the receipt code was copied for them:

Console.WriteLine(ReceiptLineForBike(new Bike(), 2));
Console.WriteLine(ReceiptLineForEBike(new EBike(), 3));

string ReceiptLineForBike(Bike bike, int hours)
{
    return quot;{bike.Name}, {hours} hours: ${bike.Price(hours)}";
}

string ReceiptLineForEBike(EBike ebike, int hours)
{
    return quot;{ebike.Name}, {hours} hours: ${ebike.Price(hours)}";
}

class Bike
{
    public string Name => "Bike";
    public int Price(int hours) => 10 * hours;
}

class EBike
{
    public string Name => "E-bike";
    public int Price(int hours) => 15 * hours;
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
class Bike {
    String name() { return "Bike"; }
    int price(int hours) { return 10 * hours; }
}

class EBike {
    String name() { return "E-bike"; }
    int price(int hours) { return 15 * hours; }
}

String receiptLineForBike(Bike bike, int hours) {
    return bike.name() + ", " + hours + " hours: quot; + bike.price(hours);
}

String receiptLineForEBike(EBike ebike, int hours) {
    return ebike.name() + ", " + hours + " hours: quot; + ebike.price(hours);
}

void main() {
    IO.println(receiptLineForBike(new Bike(), 2));
    IO.println(receiptLineForEBike(new EBike(), 3));
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
class Bike:
    name = "Bike"

    def price(self, hours):
        return 10 * hours


class EBike:
    name = "E-bike"

    def price(self, hours):
        return 15 * hours


def receipt_line_for_bike(bike, hours):
    return f"{bike.name}, {hours} hours: ${bike.price(hours)}"


def receipt_line_for_ebike(ebike, hours):
    return f"{ebike.name}, {hours} hours: ${ebike.price(hours)}"


print(receipt_line_for_bike(Bike(), 2))
print(receipt_line_for_ebike(EBike(), 3))
Bike, 2 hours: $20
E-bike, 3 hours: $45
class Bike {
  name = "Bike";
  price(hours) { return 10 * hours; }
}

class EBike {
  name = "E-bike";
  price(hours) { return 15 * hours; }
}

function receiptLineForBike(bike, hours) {
  return `${bike.name}, ${hours} hours: ${bike.price(hours)}`;
}

function receiptLineForEBike(ebike, hours) {
  return `${ebike.name}, ${hours} hours: ${ebike.price(hours)}`;
}

console.log(receiptLineForBike(new Bike(), 2));
console.log(receiptLineForEBike(new EBike(), 3));
Bike, 2 hours: $20
E-bike, 3 hours: $45
class Bike {
  name = "Bike";
  price(hours: number): number { return 10 * hours; }
}

class EBike {
  name = "E-bike";
  price(hours: number): number { return 15 * hours; }
}

function receiptLineForBike(bike: Bike, hours: number): string {
  return `${bike.name}, ${hours} hours: ${bike.price(hours)}`;
}

function receiptLineForEBike(ebike: EBike, hours: number): string {
  return `${ebike.name}, ${hours} hours: ${ebike.price(hours)}`;
}

console.log(receiptLineForBike(new Bike(), 2));
console.log(receiptLineForEBike(new EBike(), 3));
Bike, 2 hours: $20
E-bike, 3 hours: $45

In C#, Java and TypeScript, the copy was forced: ReceiptLineForBike asks for a Bike, and the compiler won't hand it an e-bike. Python and JavaScript would let one function take either, but nothing in the code says what that function needs from the thing it's given.

Scooters arrive next month, at $8 an hour. That's a third copy, and every change to the receipt (a date, a renter's name) now has to be made three times. The two functions are already the same apart from the class they ask for, and that's the clue. The receipt doesn't care whether it's a bike. It needs something with a name and a price for some hours.

A promise, written down

A store gift card works this way. The register doesn't care which store printed the card, what it's made of or what picture is on it. It cares that the card keeps one promise: it has a number the register can read, and a balance. Any card that keeps the promise works, including card designs nobody had thought of when the register was built.

In code, a written promise like that is an interface. It lists the methods (and, in some languages, the properties) a class must have, with no code inside them. A class that has every one of them implements the interface, or keeps its promise. And code can ask for the interface instead of a class:

One promise, Rentable (a name and price(hours)), kept by three classes: Bike at $10 an hour, E-bike at $15 and Scooter at $8, each with a dashed arrow labeled "keeps the promise". receiptLine asks for any Rentable, so it works with all three

Console.WriteLine(ReceiptLine(new Bike(), 2));
Console.WriteLine(ReceiptLine(new EBike(), 3));
Console.WriteLine(ReceiptLine(new Scooter(), 2));

string ReceiptLine(IRentable item, int hours)
{
    return quot;{item.Name}, {hours} hours: ${item.Price(hours)}";
}

// The promise: anything rentable has a name and a price for some hours.
interface IRentable
{
    string Name { get; }
    int Price(int hours);
}

class Bike : IRentable
{
    public string Name => "Bike";
    public int Price(int hours) => 10 * hours;
}

class EBike : IRentable
{
    public string Name => "E-bike";
    public int Price(int hours) => 15 * hours;
}

class Scooter : IRentable
{
    public string Name => "Scooter";
    public int Price(int hours) => 8 * hours;
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
// The promise: anything rentable has a name and a price for some hours.
interface Rentable {
    String name();
    int price(int hours);
}

class Bike implements Rentable {
    public String name() { return "Bike"; }
    public int price(int hours) { return 10 * hours; }
}

class EBike implements Rentable {
    public String name() { return "E-bike"; }
    public int price(int hours) { return 15 * hours; }
}

class Scooter implements Rentable {
    public String name() { return "Scooter"; }
    public int price(int hours) { return 8 * hours; }
}

String receiptLine(Rentable item, int hours) {
    return item.name() + ", " + hours + " hours: quot; + item.price(hours);
}

void main() {
    IO.println(receiptLine(new Bike(), 2));
    IO.println(receiptLine(new EBike(), 3));
    IO.println(receiptLine(new Scooter(), 2));
}
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
from abc import ABC, abstractmethod


class Rentable(ABC):
    """The promise: anything rentable has a name and a price for some hours."""
    name = ""

    @abstractmethod
    def price(self, hours):
        """What renting it costs for this many hours."""


class Bike(Rentable):
    name = "Bike"

    def price(self, hours):
        return 10 * hours


class EBike(Rentable):
    name = "E-bike"

    def price(self, hours):
        return 15 * hours


class Scooter(Rentable):
    name = "Scooter"

    def price(self, hours):
        return 8 * hours


def receipt_line(item, hours):
    return f"{item.name}, {hours} hours: ${item.price(hours)}"


print(receipt_line(Bike(), 2))
print(receipt_line(EBike(), 3))
print(receipt_line(Scooter(), 2))
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
// The promise, kept by convention: anything rentable has a name and a price(hours) method.
class Bike {
  name = "Bike";
  price(hours) { return 10 * hours; }
}

class EBike {
  name = "E-bike";
  price(hours) { return 15 * hours; }
}

class Scooter {
  name = "Scooter";
  price(hours) { return 8 * hours; }
}

function receiptLine(item, hours) {
  return `${item.name}, ${hours} hours: ${item.price(hours)}`;
}

console.log(receiptLine(new Bike(), 2));
console.log(receiptLine(new EBike(), 3));
console.log(receiptLine(new Scooter(), 2));
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16
// The promise: anything rentable has a name and a price for some hours.
interface Rentable {
  name: string;
  price(hours: number): number;
}

class Bike implements Rentable {
  name = "Bike";
  price(hours: number): number { return 10 * hours; }
}

class EBike implements Rentable {
  name = "E-bike";
  price(hours: number): number { return 15 * hours; }
}

class Scooter implements Rentable {
  name = "Scooter";
  price(hours: number): number { return 8 * hours; }
}

function receiptLine(item: Rentable, hours: number): string {
  return `${item.name}, ${hours} hours: ${item.price(hours)}`;
}

console.log(receiptLine(new Bike(), 2));
console.log(receiptLine(new EBike(), 3));
console.log(receiptLine(new Scooter(), 2));
Bike, 2 hours: $20
E-bike, 3 hours: $45
Scooter, 2 hours: $16

There's one receipt function now, and the scooter needed nothing from it. Next year's tandem bike will be one new class that keeps the promise, and the receipt will print it without a single edit.

Naming: C# starts an interface's name with a capital I (IRentable), by custom. Java, Python and TypeScript don't, so there it's Rentable. : IRentable in C#, implements Rentable in Java and TypeScript, and (Rentable) in Python each read "keeps the promise of Rentable".

Who checks the promise

The five languages agree on the idea and differ on who checks it, and when. Here's what happens if someone writes a Scooter with a name but forgets price:

Language How the promise is written If Scooter forgets price
C# interface IRentable The program won't compile: 'Scooter' does not implement interface member 'IRentable.Price(int)'
Java interface Rentable The program won't compile: Scooter is not abstract and does not override abstract method price(int) in Rentable
TypeScript interface Rentable tsc refuses it: Property 'price' is missing in type 'Scooter' but required in type 'Rentable'.
Python an abstract base class, class Rentable(ABC), with @abstractmethod on price The program runs, but making a scooter stops it: TypeError: Can't instantiate abstract class Scooter without an implementation for abstract method 'price'
JavaScript nowhere: it's a convention Everything runs until the desk calls the method: TypeError: item.price is not a function

An abstract base class in Python (ABC is short for abstract base class) is a class that can't be made into an object itself; it exists to be the parent of classes that fill in its @abstractmethods. Only the methods marked @abstractmethod are checked: the empty name = "" is a default, not a check. Python also has Protocol, from the typing module: a promise that a class keeps by having the right methods, without naming the protocol at all, checked by a type checker such as mypy before the program runs, not by Python while it runs.

JavaScript has no interface keyword. It relies on duck typing, from the old saying "if it walks like a duck and quacks like a duck, it's a duck": any object with a name and a price method will do. That's flexible, and it means a broken promise is found later, sometimes by a customer. A comment saying what the promise is, as in the code above, helps the next developer keep it.

Try it. In your language, add a Tandem at $20 an hour that keeps the promise, and print a receipt line for 3 hours. It should say Tandem, 3 hours: $60, and nothing else in the file changes.

Check yourself

2 questions to try on the lesson page.

So what

Ask for the promise, not the class: it's the move behind almost every pattern in this course, and it's what lets a new kind of thing arrive without anyone editing the code that uses it.

Key terms

Cheat sheets