I'll Be Backend
Principles · C#

Hollywood Principle: stop polling, let the framework call you

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

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

Watch the narrated video

Every step

Problem

Steps 1–5

Refactor

Steps 6–11

Payoff

Steps 12–13

C# bonus

Steps 14–16

Recap

Steps 17–18

The code: before and after

Before

class Checkout
{
    private readonly List<int> orders = [];

    public void Place(int id) => orders.Add(id);

    public List<int> OpenOrders() => orders;
}

class Packing
{
    private int lastSeen;

    public void Check(Checkout checkout)
    {
        List<int> open = checkout.OpenOrders();
        for (int i = lastSeen; i < open.Count; i++)
        {
            Console.WriteLine($"pack {open[i]}");
        }
        lastSeen = open.Count;
    }
}

class Invoicing
{
    private int lastSeen;

    public void Check(Checkout checkout)
    {
        List<int> ids = checkout.OpenOrders();
        for (int i = lastSeen; i < ids.Count; i++)
        {
            Console.WriteLine($"invoice {ids[i]}");
        }
        lastSeen = ids.Count;
    }
}

static class Shop
{
    public static void Main()
    {
        var checkout = new Checkout();
        var packing = new Packing();
        var 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

class Checkout
{
    private readonly List<int> orders = [];

    public event Action<int>? Placed;

    public void Place(int id)
    {
        orders.Add(id);
        Placed?.Invoke(id);
    }

    public void Cancel(int id) => orders.Remove(id);
}

class Packing
{
    public void OrderPlaced(int id) =>
        Console.WriteLine($"pack {id}");
}

class Invoicing
{
    public void OrderPlaced(int id) =>
        Console.WriteLine($"invoice {id}");
}

static class Shop
{
    public static void Main()
    {
        var checkout = new Checkout();
        var packing = new Packing();
        var invoicing = new Invoicing();
        checkout.Placed += packing.OrderPlaced;
        checkout.Placed += invoicing.OrderPlaced;
        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. The output is pack and invoice for each of the two orders. 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. 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, the order listener interface, 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 replays the old tick three: it cancels 101, then places 103. What does the output say about order 103 this time?

Step 13: Nothing missed Payoff

Pack 103 and invoice 103, because Place calls each listener the moment the order exists. Packing and Invoicing didn't change at all. Packing and Invoicing have no loop that guesses now, so 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.

C# bonus

Step 14: A list we wrote by hand C# bonus

But Checkout still carries a hand-written list of listeners, a Subscribe method, and a loop that calls each one. C sharp can keep that list for us, and a class member that does this is an event.

Step 15: An event called Placed C# bonus

So Checkout declares a public event called Placed, of type Action of int, where the list and Subscribe were. Place raises it with Placed, question mark, Invoke, which calls every handler and skips the call while there is none. Main adds each Order Placed method to the event with plus equals, and the output is the same six lines. But the event now holds a reference to Packing and Invoicing, so a part that leaves must remove itself with minus equals.

Step 16: Drop the unused interface Remove Dead Code

Nothing refers to the order listener interface anymore, so we delete it, and Packing and Invoicing become plain classes. Checkout still knows neither class, because its event only holds methods that take an order id.

Recap

Step 17: 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 raises its event the moment an order is placed. And each handler, like Packing's Order Placed, only says what happens to one order.

Step 18: 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. If a part keeps its own count of what it already saw, it's polling. In dot net, you hand File System Watcher a method, and it calls you when a file appears.