I'll Be Backend
Principles · Java

Hollywood Principle: stop polling, let the framework call you

Let Checkout tell each part about an order, so none is missed.

16 steps5 chapters~6 min at 1.25×#hollywood principle#observer#polling#listeners
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Java video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–5

Refactor

Steps 6–11

Payoff

Step 12

Java bonus

Steps 13–14

Recap

Steps 15–16

The code: before and after

Before

class Checkout {
    private final List<Integer> orders = new ArrayList<>();

    void place(int id) {
        orders.add(id);
    }

    List<Integer> openOrders() {
        return orders;
    }
}

class Packing {
    private int lastSeen;

    void check(Checkout checkout) {
        List<Integer> open = checkout.openOrders();
        for (int i = lastSeen; i < open.size(); i++) {
            System.out.println("pack " + open.get(i));
        }
        lastSeen = open.size();
    }
}

class Invoicing {
    private int lastSeen;

    void check(Checkout checkout) {
        List<Integer> ids = checkout.openOrders();
        for (int i = lastSeen; i < ids.size(); i++) {
            System.out.println("invoice " + ids.get(i));
        }
        lastSeen = ids.size();
    }
}

class Shop {
    public static void main(String[] args) {
        Checkout checkout = new Checkout();
        Packing packing = new Packing();
        Invoicing invoicing = new Invoicing();
        // tick 1
        checkout.place(101);
        packing.check(checkout);
        invoicing.check(checkout);
        // tick 2
        checkout.place(102);
        packing.check(checkout);
        invoicing.check(checkout);
        // tick 3
        packing.check(checkout);
        invoicing.check(checkout);
    }
}

After

interface OrderListener {
    void orderPlaced(int id);
}

class Checkout {
    private final List<Integer> orders = new ArrayList<>();
    private final List<OrderListener> listeners =
            new ArrayList<>();

    void subscribe(OrderListener listener) {
        listeners.add(listener);
    }

    void place(int id) {
        orders.add(id);
        for (OrderListener listener : listeners) {
            listener.orderPlaced(id);
        }
    }

    void cancel(int id) {
        orders.remove(Integer.valueOf(id));
    }
}

class Packing implements OrderListener {
    public void orderPlaced(int id) {
        System.out.println("pack " + id);
    }
}

class Shop {
    public static void main(String[] args) {
        Checkout checkout = new Checkout();
        Packing packing = new Packing();
        checkout.subscribe(packing);
        checkout.subscribe(id -> System.out.println("invoice " + id));
        checkout.place(101);
        checkout.place(102);
        checkout.cancel(101);
        checkout.place(103);
    }
}

Transcript, step by step

Problem

Step 1: Two parts that poll Before

This is a shop's checkout, and placing an order adds its id to a list of open orders. Packing asks Checkout for that list, prints pack for every id past last seen, then moves last seen to the end. Invoicing does the same, with invoice instead of pack. Main runs three ticks, and each tick may place an order, then lets both parts check for new ones. Tick three places nothing, so both checks find nothing new, and the output is pack and invoice for 101 and 102. Both parts poll Checkout here, asking it each tick whether anything is new. Checkout knows nothing about packing or invoicing, and asking each tick was the shortest way to find new orders.

Step 2: Customers can cancel Change request

Now customers can cancel an order, and a cancelled order leaves the open list. The quick edit adds a cancel method to Checkout, which removes that id from the list. Tick three now cancels order 101 and places order 103, then lets packing and invoicing check as before. It compiles, so what does tick three print? Nothing at all, so order 103 is never packed and never invoiced, and no error tells us.

Step 3: A guess from the length Code smell

After the cancel and the new order, the list is two long, and last seen is still two. Each part polls Checkout and guesses what's new from the list's length. So when a cancel and a new order land between two polls, they hide each other from that guess. You can see it in Packing's loop here, the same loop in Invoicing here, and the cancel that breaks it here. Order 103 is never packed and never invoiced, yet the program runs without a single error. And the same guess lives in each part, so a fix has to be made in every poller.

Step 4: Let the source call Principle

We could fix the guess in both loops, but every new poller would have to repeat that fix. Only Checkout knows the moment an order exists, so Checkout should call each part at that moment. Low-level parts don't call the source to ask, the source calls them, and that rule is the Hollywood Principle. Its short form is don't call us, we'll call you. So now: Checkout must call each part, and no part asks.

Step 5: Refactor first Back it out

So we take cancel back out, and tick three is an empty poll again. We refactor first in small steps, with the same four lines of output each time, and cancel comes back at the end.

Refactor

Step 6: Packing's work per order Extract Method

So in Packing, we extract the print into its own method, order placed, which takes one order id. The loop now calls order placed for each new id, and the output is the same.

Step 7: Invoicing's work per order Extract Method

Invoicing gets the same move, with its invoice print in its own order placed method. Its loop calls that method too, and the output still has the same four lines.

Step 8: Name the listener Extract Interface

Both methods have the same shape, so we extract an interface, Order Listener, with that one method. Packing and Invoicing now implement it, though nothing calls them through the interface yet.

Step 9: Checkout calls Packing Apply Observer

Now Checkout keeps a list of listeners, and its subscribe method adds one to that list. After place adds the id, it calls order placed on every listener, and that call is a notification. Checkout calls listeners it only knows through one interface, and that design is the Observer pattern. In that pattern, Checkout plays the Subject and Packing plays an Observer. Main subscribes Packing and stops calling its check, and each tick still prints pack before invoice.

Step 10: Checkout calls Invoicing Apply Observer

Invoicing gets the same move, so main subscribes it and stops calling its check. Now no part asks Checkout anything, because Checkout calls each listener from the loop in place. Invoicing is an Observer too, and the output is still the same four lines.

Step 11: Delete the polling Remove Dead Code

Both check methods, both last seen fields, and open orders had no callers left. So we delete them, and main shrinks to two subscribes and two orders, with the same four lines out.

Payoff

Step 12: Cancel, take two Payoff

So now cancel comes back, the same method in Checkout as before. Main places 101 and 102, then cancels 101 and places 103, just like the old tick three. What does the output say about order 103 this time? Pack 103 and invoice 103, because place calls each listener the moment the order exists. Packing and Invoicing didn't change at all. Where Packing's loop and Invoicing's loop guessed, there's no loop now, and cancel can't hide 103 anymore. The parts stopped calling Checkout and Checkout calls them, just as the Hollywood Principle says. But to follow one order now, you read the loop in place and then every listener it calls.

Java bonus

Step 13: A class for one print Java bonus

But Invoicing is a whole class, five lines long, for one print line. Order Listener has exactly one abstract method, and Java calls an interface like that a functional interface.

Step 14: A listener as a lambda Java bonus

So main can subscribe a lambda that takes the id and prints invoice and the id. The Invoicing class is gone, and the output is the same, because place calls the lambda as a listener. A lambda has no name of its own, so keep a class like Packing once a listener grows past one line.

Recap

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

On the left, Packing and Invoicing each polled Checkout and guessed new orders from the list's length. So a cancel between two polls could hide a brand-new order from both of them. On the right, Checkout calls every listener the moment an order is placed. And each listener, even the lambda, only says what happens to one order.

Step 16: When to reach for it Takeaways

Reach for it when several parts must react to something that happens in one place. If nothing can call you back, like an outside API with no webhook, you have to keep asking. Spot it by a counter like last seen, or a loop that asks the source whether anything is new. Java beans already work this way, because Property Change Support calls every listener you add.