CSE Roadmap

Core tier · about 2 hours · 6 parts

Part 3 of 6 · 2 min read

Program to an interface

The first principle of reusable design in GoF.

GoF gives this as the first of two principles for reusable object-oriented design: depend on an interface and never on a concrete implementation. Do not declare variables as instances of particular concrete classes. Commit only to an interface.

The book names two benefits. Clients stay unaware of the specific classes of the objects they use, as long as those objects meet the expected interface. And clients stay unaware of which classes implement them, because they know only the interface. That cuts the dependencies between parts of a system.

The idea shows up in everyday Java:

List<String> names = new ArrayList<>();

The variable is declared as the interface List, and only the new names the concrete class. Changing to LinkedList later is a one-word edit on that line. Everything else in the program keeps working, because it only calls List methods.

A made-up payment example:

interface PaymentMethod {
    boolean pay(long cents);
}

class Card implements PaymentMethod {
    public boolean pay(long cents) { return cents <= 100_000; }
}

class Wallet implements PaymentMethod {
    private long balance;
    Wallet(long balance) { this.balance = balance; }
    public boolean pay(long cents) {
        if (cents > balance) return false;
        balance -= cents;
        return true;
    }
}

class Checkout {
    boolean checkout(PaymentMethod method, long cents) {
        return method.pay(cents);
    }
}

Checkout knows only PaymentMethod. Adding a new method, such as bank transfer, needs one new class and no change to Checkout. With a wallet of 5,000 cents, checkout(wallet, 3000) is true and a second checkout(wallet, 3000) is false. This was run to confirm.

Somewhere a concrete class must still be named. GoF notes that the creational patterns (Level 3) exist to do that in a way that keeps the rest of the system written in terms of interfaces.

Common mistake

Declaring ArrayList<String> names and passing it everywhere. Every method that receives it is now tied to one class.

Check yourself: 1. What is the one place in the List example that names the concrete class? 2. What changes in Checkout when a new payment method is added? 3. What do the creational patterns do for this principle?