I'll Be Backend
Principles · PHP

Interface Segregation: split a fat interface

Give each caller an interface with only the methods it calls.

14 steps4 chapters~6 min at 1.25×#solid#interfaces#isp#decoupling
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the PHP video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–10

Payoff

Steps 11–12

Recap

Steps 13–14

The code: before and after

Before

interface Inventory
{
    public function stockOf(string $sku): int;

    public function reserve(string $sku, int $qty): void;

    public function restock(string $sku, int $qty): void;
}

final class WarehouseInventory implements Inventory
{
    /** @var array<string, int> */
    private array $counts = ['mug' => 12];

    public function stockOf(string $sku): int
    {
        return $this->counts[$sku];
    }

    public function reserve(string $sku, int $qty): void
    {
        $this->counts[$sku] -= $qty;
        echo "reserved {$qty} {$sku}\n";
    }

    public function restock(string $sku, int $qty): void
    {
        $this->counts[$sku] += $qty;
        echo "restocked {$qty} {$sku}\n";
    }
}

final class ProductPage
{
    public function show(Inventory $stock, string $sku): void
    {
        $count = $stock->stockOf($sku);
        echo "{$sku}: {$count} in stock\n";
    }
}

final class Checkout
{
    public function buy(Inventory $stock, string $sku, int $qty): void
    {
        $stock->reserve($sku, $qty);
    }
}

final class Receiving
{
    public function receive(Inventory $stock, string $sku, int $qty): void
    {
        $stock->restock($sku, $qty);
    }
}

$warehouse = new WarehouseInventory();
(new ProductPage())->show($warehouse, 'mug');
(new Checkout())->buy($warehouse, 'mug', 2);
(new Receiving())->receive($warehouse, 'mug', 5);

After

interface StockLevels
{
    public function stockOf(string $sku): int;
}

interface Reservations
{
    public function reserve(string $sku, int $qty): void;
}

interface Restocking
{
    public function restock(string $sku, int $qty): void;
}

interface Inventory extends StockLevels, Reservations, Restocking
{
}

final class WarehouseInventory implements Inventory
{
    /** @var array<string, int> */
    private array $counts = ['mug' => 12];

    public function stockOf(string $sku): int
    {
        return $this->counts[$sku];
    }

    public function reserve(string $sku, int $qty): void
    {
        $this->counts[$sku] -= $qty;
        echo "reserved {$qty} {$sku}\n";
    }

    public function restock(string $sku, int $qty): void
    {
        $this->counts[$sku] += $qty;
        echo "restocked {$qty} {$sku}\n";
    }
}

final class CachedStock implements StockLevels
{
    /** @param array<string, int> $levels */
    public function __construct(
        private readonly array $levels,
    ) {}

    public function stockOf(string $sku): int
    {
        return $this->levels[$sku];
    }
}

final class ProductPage
{
    public function show(StockLevels $stock, string $sku): void
    {
        $count = $stock->stockOf($sku);
        echo "{$sku}: {$count} in stock\n";
    }
}

final class Checkout
{
    public function buy(Reservations $stock, string $sku, int $qty): void
    {
        $stock->reserve($sku, $qty);
    }
}

final class Receiving
{
    public function receive(Restocking $stock, string $sku, int $qty): void
    {
        $stock->restock($sku, $qty);
    }
}

$warehouse = new WarehouseInventory();
$cache = new CachedStock(['mug' => 12]);
(new ProductPage())->show($cache, 'mug');
(new Checkout())->buy($warehouse, 'mug', 2);
(new Receiving())->receive($warehouse, 'mug', 5);

Transcript, step by step

Problem

Step 1: A shop that tracks stock Before

Inventory is an interface with three methods, stock of, reserve and restock. Warehouse Inventory implements all three over an array, and it starts with twelve mugs. Three small classes call it, and each one needs a different method. Product Page calls only stock of, Checkout calls only reserve, and Receiving calls only restock. The script at the bottom hands the warehouse to all three, and the page prints mug, twelve in stock. Every caller so far talks to the warehouse, so one interface for all of them looked fine.

Step 2: The page reads a cache Code smell

The product page gets heavy traffic, so it must read stock from a cache instead of the warehouse. The quick way adds Cached Stock, a class over an array of counts, and makes it implement Inventory. Its stock of reads that array, which is all the page needs. But Inventory also demands reserve and restock, and PHP stops with a fatal error when a class skips one. A read-only cache has nothing useful to put in them, so Cached Stock throws a Logic Exception from both. The script now hands the cache to the product page, and it still prints mug, twelve in stock.

Step 3: A fat interface Code smell

Inventory is a fat interface, which means it has more methods than any one caller uses. Cached Stock writes reserve here and restock here only to throw, because Product Page asks for an Inventory here. You might think the stubs are harmless, because the page never calls them. So what happens if the script hands the cache to Checkout instead? Checkout asks for an Inventory, so PHP and PHPStan accept the cache, and the first sale throws a Logic Exception. The rule that gives each caller an interface with only the methods it calls is the Interface Segregation Principle.

Refactor

Step 4: Refactor first Back it out

We take Cached Stock back out, so the shop runs on the warehouse alone again. Then we split Inventory one caller at a time, and the cache comes back once the page asks for less.

Step 5: Stock levels on their own Extract Interface

First, stock of moves into an interface of its own called Stock Levels. Inventory extends Stock Levels and drops its own copy, so it still offers all three methods. Warehouse Inventory doesn't change, and nothing asks for a Stock Levels yet.

Step 6: The page asks for StockLevels Change Function Declaration

Product Page's parameter becomes a Stock Levels, because stock of is the only method it calls. The script still passes the warehouse, and PHPStan accepts it, because Inventory extends Stock Levels. So now the page needs only stock of, and Checkout and Receiving still ask for all three.

Step 7: Reservations on their own Extract Interface

But Checkout still asks for all three methods, so reserve moves into a second small interface called Reservations. Inventory now extends Stock Levels and Reservations, so it still offers the same three methods.

Step 8: Checkout asks for Reservations Change Function Declaration

Checkout only reserves, so its parameter becomes a Reservations. The script passes the same warehouse to it, and the program still prints reserved two mug.

Step 9: Restocking on its own Extract Interface

But Receiving still asks for all three, so restock moves into an interface called Restocking. An interface shaped by what one caller does is a role interface. Inventory now declares nothing of its own, and it only joins the three small interfaces together.

Step 10: Receiving asks for Restocking Change Function Declaration

Receiving only restocks, so its parameter becomes a Restocking. Warehouse Inventory still implements Inventory, and its code hasn't changed since we started. We keep the empty Inventory interface, because that one name on the warehouse says it fills all three. Each caller now asks for the one interface it calls, and the warehouse fits all three.

Payoff

Step 11: The cache comes back Payoff

So the cache from the start of the video can come back in. Cached Stock implements Stock Levels alone, so it writes one method and has nothing to throw. The script hands it to the page, and the page prints mug, twelve in stock, like before.

Step 12: Nothing else changed Payoff

Warehouse Inventory, Checkout and Receiving didn't change to add the cache. Cached Stock implements one interface here, writes one method here, and Product Page asks only for Stock Levels here. The cache has no stubs left, because no caller makes it carry a method it never uses. Hand the cache to Checkout, and PHPStan objects before the script runs, since Cached Stock isn't a Reservations. Run it anyway, and PHP throws a Type Error here, before any code inside Checkout starts. That's the Interface Segregation Principle, with each caller seeing only the methods it calls. But a new caller that reads and reserves must spell out Stock Levels and Reservations together in its signature. And the shop now has four interfaces where it had one.

Recap

Step 13: Where we started, where we ended Before / after

On the left, one Inventory interface gave every caller all three methods. So anything handed to the product page had to write reserve and restock as well. On the right, each method has its own role interface, and Inventory only joins them. Product Page asks only for Stock Levels, so the cache had to write that one method alone.

Step 14: When to reach for it Takeaways

Reach for it when an implementation throws in methods its callers never call, or each caller uses a different slice. Skip it when every caller uses the whole interface, like a small repository whose one service calls both find and save. You'll spot it by stubs that only throw, like Cached Stock's reserve, or by test doubles stubbing methods the test never calls. PHP's own count function works this way, because for objects it asks only for Countable, an interface with one method.