Skip to lesson

Program to interfaces: designing the seams

ShopLite's Checkout creates a CardGateway by itself, so it cannot be tested without charging a real card and cannot switch to UPI without being edited. This lesson shows how to design the joins between classes so both are easy.

Declared type vs runtime type

The declared type is the type written on a variable, field, parameter or return value, like PaymentGateway in PaymentGateway gateway = new CardGateway();. The runtime type is the real object's class, here CardGateway.

Checkout should not care which payment class does the work. Below, a field, a parameter and a return value are all declared with an interface type.

Example 1 · Declared types in a field, a parameter and a return value

DeclaredTypeDemo.javaJava
import java.util.ArrayList;import java.util.List;
interface PaymentGateway {    boolean charge(String orderId, double amount);}
class CardGateway implements PaymentGateway {    public boolean charge(String orderId, double amount) {        System.out.printf("Card: charged Rs %.2f for %s%n", amount, orderId);        return true;    }
    String network() {        return "RuPay";    }}
class OrderHistory {    private final List<String> ids = new ArrayList<>();   // field: declared List, runtime ArrayList
    void add(String id) {        ids.add(id);    }
    List<String> recent() {        return List.copyOf(ids);    }}
public class DeclaredTypeDemo {    static void pay(PaymentGateway gateway, String orderId, double amount) {   // parameter: interface        gateway.charge(orderId, amount);    }
    public static void main(String[] args) {        PaymentGateway gateway = new CardGateway();        System.out.println("Declared: PaymentGateway, runtime: " + gateway.getClass().getSimpleName());        pay(gateway, "ORD-11", 999);        // gateway.network();   // does not compile: PaymentGateway has no network()
        OrderHistory history = new OrderHistory();        history.add("ORD-11");        history.add("ORD-12");        List<String> recent = history.recent();        System.out.println(recent + ", is it an ArrayList? " + (recent instanceof ArrayList));    }}
Output
Declared: PaymentGateway, runtime: CardGateway
Card: charged Rs 999.00 for ORD-11
[ORD-11, ORD-12], is it an ArrayList? false

What this code does

  • gateway is declared as PaymentGateway, so gateway.network() would not compile even though the real object is a CardGateway.
  • recent() promises only a List. It returns an unmodifiable copy, not an ArrayList, and callers never noticed: that freedom is what the declared type buys.

The compiler checks every call against the declared type, so you can call only methods the interface has. At run time Java calls the method of the real object, so callers keep working when the real class changes.

Common mistake: calling a method only the real class has, like the commented gateway.network(). It does not compile against the interface.

Fix the error

Call only what the interface promises

Read the real compiler error, then pick the line that fixes it.

The code must print the result of a payment.

interface PaymentGateway { boolean charge(String id, double amount); }
class CardGateway implements PaymentGateway {
public boolean charge(String id, double amount) { return true; }
String network() { return "VISA"; }
}
PaymentGateway gateway = new CardGateway();
System.out.println(gateway.network());

Error

Main.java:7: error: cannot find symbol
        System.out.println(gateway.network());
  symbol:   method network()
  location: variable gateway of type PaymentGateway

Finding the seams

A seam is a place where you can change behaviour without editing the code around it. In Java, a seam is usually an interface that a class receives instead of creating.

Put seams where change is likely. Below, the payment provider and the notifier get interfaces, while a stable price rule stays a plain class.

Java
// Likely to change: an interface (a seam)interface PaymentGateway { boolean charge(String orderId, double amount); }interface NotificationService { void send(String to, String text); }
// Owned and stable: a plain class is enoughclass PriceCalculator {    double total(double itemsTotal, double deliveryFee) { return itemsTotal + deliveryFee; }}

Not everything needs a seam. In ShopLite the payment provider may switch (a card network today, a new UPI partner next year) and the notification channel grows (email, then SMS, then WhatsApp). Pricing rules that ShopLite owns and tests directly can stay plain classes.

A quick test for a seam: does this talk to the outside world (network, money, time, files), or will a second version arrive soon? If yes, put an interface there.

Constructor injection by hand

Constructor injection means a class receives the objects it depends on as constructor parameters and stores them in final fields, instead of creating them with new inside.

Checkout asks for a PaymentGateway and a NotificationService in its constructor and never calls new on a concrete gateway. Below, main builds the real objects and passes them in.

Checkout depends only on the PaymentGateway interface. The real CardGateway and a test FakeGateway both implement it. main or Spring builds the chosen one and passes it in, so swapping real for fake changes nothing in Checkout.

Example 2 · Checkout receives its gateway and notifier

ConstructorInjectionDemo.javaJava
import java.util.Objects;
interface PaymentGateway {    boolean charge(String orderId, double amount);}
interface NotificationService {    void send(String to, String text);}
class CardGateway implements PaymentGateway {    public boolean charge(String orderId, double amount) {        System.out.printf("Card: charged Rs %.2f for %s%n", amount, orderId);        return true;    }}
class UpiGateway implements PaymentGateway {    public boolean charge(String orderId, double amount) {        if (amount > 100000) {                       // a simplified per-payment limit            System.out.printf("UPI: Rs %.2f is above the Rs 1,00,000 limit%n", amount);            return false;        }        System.out.printf("UPI: collected Rs %.2f for %s%n", amount, orderId);        return true;    }}
class EmailNotification implements NotificationService {    public void send(String to, String text) {        System.out.println("Email to " + to + ": " + text);    }}
class SmsNotification implements NotificationService {    public void send(String to, String text) {        System.out.println("SMS to " + to + ": " + text);    }}
class Checkout {    private final PaymentGateway gateway;    private final NotificationService notifications;
    Checkout(PaymentGateway gateway, NotificationService notifications) {        this.gateway = Objects.requireNonNull(gateway);        this.notifications = Objects.requireNonNull(notifications);    }
    String placeOrder(String orderId, String contact, double amount) {        if (!gateway.charge(orderId, amount)) {            notifications.send(contact, orderId + " payment failed");            return "FAILED";        }        notifications.send(contact, orderId + " confirmed");        return "CONFIRMED";    }}
public class ConstructorInjectionDemo {    public static void main(String[] args) {        // main is the only place that names concrete classes        Checkout cardAndEmail = new Checkout(new CardGateway(), new EmailNotification());        Checkout upiAndSms = new Checkout(new UpiGateway(), new SmsNotification());
        System.out.println(cardAndEmail.placeOrder("ORD-21", "asha@mail.com", 2499));        System.out.println(upiAndSms.placeOrder("ORD-22", "9876543210", 349));        System.out.println(upiAndSms.placeOrder("ORD-23", "9876543210", 150000));    }}
Output
Card: charged Rs 2499.00 for ORD-21
Email to asha@mail.com: ORD-21 confirmed
CONFIRMED
UPI: collected Rs 349.00 for ORD-22
SMS to 9876543210: ORD-22 confirmed
CONFIRMED
UPI: Rs 150000.00 is above the Rs 1,00,000 limit
SMS to 9876543210: ORD-23 payment failed
FAILED

What this code does

  • The same Checkout class runs with card plus email and with UPI plus SMS. Only main, the composition root, names concrete classes.
  • Objects.requireNonNull makes a missing dependency fail at construction time with a clear stack trace, not later in the middle of an order.

The place that builds the real objects and connects them is called the composition root. In a small program it is main. In ShopLite's Spring Boot API, Spring plays that role: it calls the constructors and passes the beans in, the same idea done for you.

Common mistake: forgetting to store a constructor parameter in its field. The field stays null and the program fails later with a NullPointerException.

Order of execution

Wire a Checkout by hand

Put the steps in the order you write them.

Swapping in a fake for a test

A fake is a small, simple implementation of an interface written for testing. A fake gateway approves or declines on command and remembers every charge, with no network and no real money.

A fake lets a test choose what happens. Below, main passes fakes into Checkout and then checks what they recorded.

Example 3 · Testing checkout with fakes in main

CheckoutFakeTestDemo.javaJava
import java.util.ArrayList;import java.util.List;
interface PaymentGateway {    boolean charge(String orderId, double amount);}
interface NotificationService {    void send(String to, String text);}
class Checkout {    private final PaymentGateway gateway;    private final NotificationService notifications;
    Checkout(PaymentGateway gateway, NotificationService notifications) {        this.gateway = gateway;        this.notifications = notifications;    }
    String placeOrder(String orderId, String contact, double amount) {        if (!gateway.charge(orderId, amount)) {            notifications.send(contact, orderId + " payment failed");            return "FAILED";        }        notifications.send(contact, orderId + " confirmed");        return "CONFIRMED";    }}
// Fakes: no network, no money, and they remember what happenedclass FakeGateway implements PaymentGateway {    final List<String> charges = new ArrayList<>();    private final boolean approve;
    FakeGateway(boolean approve) {        this.approve = approve;    }
    public boolean charge(String orderId, double amount) {        charges.add(orderId + "=" + amount);        return approve;    }}
class RecordingNotifications implements NotificationService {    final List<String> messages = new ArrayList<>();
    public void send(String to, String text) {        messages.add(to + ": " + text);    }}
public class CheckoutFakeTestDemo {    static int failures = 0;
    static void check(String name, boolean ok) {        System.out.println((ok ? "PASS " : "FAIL ") + name);        if (!ok) failures++;    }
    public static void main(String[] args) {        FakeGateway approving = new FakeGateway(true);        RecordingNotifications inbox = new RecordingNotifications();        String result = new Checkout(approving, inbox).placeOrder("ORD-31", "asha@mail.com", 500);        check("approved payment confirms the order", result.equals("CONFIRMED"));        check("gateway charged once with the right amount", approving.charges.equals(List.of("ORD-31=500.0")));        check("customer told it is confirmed", inbox.messages.equals(List.of("asha@mail.com: ORD-31 confirmed")));
        FakeGateway declining = new FakeGateway(false);        RecordingNotifications inbox2 = new RecordingNotifications();        String result2 = new Checkout(declining, inbox2).placeOrder("ORD-32", "ravi@mail.com", 800);        check("declined payment fails the order", result2.equals("FAILED"));        check("customer told payment failed", inbox2.messages.equals(List.of("ravi@mail.com: ORD-32 payment failed")));
        System.out.println(failures == 0 ? "All checks passed" : failures + " check(s) failed");    }}
Output
PASS approved payment confirms the order
PASS gateway charged once with the right amount
PASS customer told it is confirmed
PASS declined payment fails the order
PASS customer told payment failed
All checks passed

What this code does

  • FakeGateway(false) makes the decline path easy to test. With a real card gateway you would need a real card that fails.
  • The fakes record what Checkout did, so the checks can look at the exact charge (ORD-31=500.0) and the exact message.

Because Checkout knows only the interfaces, the test needs no network and no real money. These main-method checks are the same idea that JUnit tests write with assertEquals, as in the Testing section.

Over-abstraction: when an interface is not worth it

Over-abstraction is adding layers that buy nothing, such as an interface with one class that will never have a second version and nothing slow or external to fake.

A common sign is DeliveryFeeCalculator with exactly one DeliveryFeeCalculatorImpl. Below, the same rule is written both ways.

Example 4 · An interface that adds nothing

OverAbstractionDemo.javaJava
// An interface with one implementation that is never going to changeinterface DeliveryFeeCalculator {    double fee(double orderTotal);}
class DeliveryFeeCalculatorImpl implements DeliveryFeeCalculator {    public double fee(double orderTotal) {        return orderTotal >= 499 ? 0 : 40;    }}
// The same rule as a plain class: one type, no extra layerclass DeliveryFee {    double fee(double orderTotal) {        return orderTotal >= 499 ? 0 : 40;    }}
public class OverAbstractionDemo {    public static void main(String[] args) {        DeliveryFeeCalculator viaInterface = new DeliveryFeeCalculatorImpl();        DeliveryFee plain = new DeliveryFee();        for (double total : new double[] {250, 499, 1200}) {            System.out.printf("Rs %.0f -> fee Rs %.0f (interface) / Rs %.0f (plain)%n",                    total, viaInterface.fee(total), plain.fee(total));        }    }}
Output
Rs 250 -> fee Rs 40 (interface) / Rs 40 (plain)
Rs 499 -> fee Rs 0 (interface) / Rs 0 (plain)
Rs 1200 -> fee Rs 0 (interface) / Rs 0 (plain)

What this code does

  • Both versions give the same fees. The interface version has two types for one rule and an Impl class name that only repeats the interface name.
  • The delivery fee is ShopLite's own pure calculation: nothing slow, nothing external, no second version. A plain class is easier to read and just as easy to test.

Such an interface doubles the files and makes "Go to definition" land on an empty method signature. Add an interface when a second implementation or a test fake really needs it; an IDE's Extract Interface refactoring makes that a two-minute change later.

Next step

Check your understanding

11 quick questions