Ch.5: Design Patterns: Use Observer Without Hidden Dependencies

Outline

Transcript

0:00 Observer lets an object notify registered recipients when it changes. That's useful when those recipients can vary, but we still have to decide who stays connected. We'll build it in a document editor, disconnect a closed preview, and check when updates need an order. Imagine a user editing the document after closing its preview. The closed preview still gets called, throws an error, and the word counter stops updating. Closed, but still taking calls. Here, the document holds a list of callbacks, functions it will call when the text changes.

0:31 Closing our preview didn't remove its callback. Look at that list. Preview is still first. It fails before the counter gets a turn, even though the document already holds the text one two. Remove the preview's subscription, and the counter reaches 2. Let's follow the objects behind that change, then check what happens when the recipients depend on each other. The list makes the call, not the view's flag. How does our document get those callbacks? First, the publisher is Document, the object sending change notifications.

1:01 Preview and Word Counter are subscribers. Each offers an update method receiving an event, a value carrying the changed text. Counter is created before Preview. Look at Preview's setup code, which runs when we create it. Which callback goes on the list first? Preview's. That call registers its method. Counter joins on the last line. Creation and registration are separate here. Refactoring Guru's Observer guide shows this shared-callback mechanism; we've linked it in the description. So Document keeps a way to call each recipient without a separate branch for every class.

1:35 Right. Subscribe stores the callback if it's missing, so this example doesn't register the same method twice. Yeah, a spell-check function could join later without changing the document's notification method. A plain function can subscribe too. Every registered function receives the same kind of event. What happens when we edit the text? Now follow the replacement method. First, it changes the document's text. Next, it creates an event containing that text. This event is a fixed value for the notification, so both observers can work from the same input.

2:07 So does freezing the event also freeze the recipient list? No. The event keeps the text unchanged. The loop separately copies the registered callbacks for this edit. Removing a callback afterward won't change the copy. Suppose an earlier callback removes Preview's callback. Does this edit still call Preview? Yes. Preview stays open in this example. That first callback changes the registered list. This edit's copied list still contains Preview, so it calls that method. The next edit copies the new list and skips Preview.

2:39 Even that removed callback still runs before the replacement method returns. That's synchronous execution here. Each callback returns before the loop calls the next; nothing starts a background job or sends a network message. That's our implementation's order, though. The Observer name alone doesn't tell another library which callback runs first. We'd check that library's documented rules before relying on an order. My first thought was to trust the two arrows. But they only identify recipients.

3:07 They don't tell me when either runs, or what an error will do. Those arrows leave out time, and whether every recipient finishes. Next, consider a preview closing after it subscribed. The broken method changes its closed flag, but leaves the registration. A common mistake is assuming those are the same operation. So fixing the close flag won't help. We need to change the list that actually drives those calls. Exactly. The corrected method unsubscribes this preview's update method, then sets the flag. Preview created the subscription; here it also owns removing it when its view closes.

3:42 Sure. The removal method checks whether the callback is present. That makes closing twice harmless here. A later edit now calls Counter without entering the closed preview. Hold on. Does saving that method keep the preview around too? Here it does. The diagram shows Document holding this preview's update method, which also keeps the Preview object alive. Closing a view isn't the same as destroying its object. Deleting another variable wouldn't remove that connection. Microsoft's Observer guide makes removing that connection explicit too.

4:15 I'd want our code to show who owns cleanup, even if a library provides the helper. Let's test what the caller gets from that bad subscription. Now suppose the bad subscription is still there. Inside Preview's update method, the closed check raises an exception, an error passed back to the caller. Our notification loop has nothing that catches it. So can the caller treat that exception as a rejected edit? No. The text assignment already ran. With Preview first, the document contains one two, the counter is still 0, and the caller receives the error.

4:47 The error doesn't undo that earlier work. Would moving Counter first at least let it finish? It counts both words before Preview fails. Awkward: the text changed, Counter updated, and the caller still gets an error. Reordering hasn't removed the subscription. Could we keep notifying if we report the preview failure? Yes. We could choose to report an optional display error and continue notifying other views. That's a different error policy we'd implement deliberately. Catching everything and silently calling the whole edit successful wouldn't tell us which views updated.

5:22 And if a check must reject the edit, it belongs before we change the text. A notification after the change is a poor place to hide a required validation step. So that error doesn't tell me how much completed. I'd inspect the document before deciding what to do next. But successful callbacks can hide a dependency too. Suppose Preview reads Counter's stored count for its label. That's the arrow crossing between the observers on screen. With Preview registered first, it reads 0. Counter then computes 2.

5:53 Reverse them, and Preview sees 2. Document doesn't name Preview or Counter, but Preview still needs Counter's result. We can make these displays independent. This preview calculates its label from the event's text, just as Counter does. The expression on screen splits one two into two words and counts them. Nice, both displays now reach 2 in either order. Their callbacks still run in different orders. What we've removed is Preview's need for Counter to have finished first. Computing that tiny value twice is fine for our example.

6:24 If deriving it were expensive, we could compute the shared result once and pass it as part of the event. Recipients must still agree on what the event contains and what those values mean. I'd test both registration orders. One passing order can conceal the dependency we're trying to remove, especially when somebody adds another subscriber later. That gives us independent displays for this input. But what if one display actually requires another component's result? Then we should make that dependency explicit.

6:53 For example, this small coordinator computes the count and passes the required result directly into rendering. Now the dependency is visible in two lines. If measurement raises an error, rendering isn't reached. That's a property of this sequence, not something the Observer pattern gives us. I think direct calls are easier to inspect for this fixed pair. The tradeoff changes when recipients vary. In a larger editor, who should carry Counter's required result to Preview? A central object could receive the edit, ask Counter for the count, then pass it to Preview.

7:27 That's Mediator: one object organizes how the components work together. Counter and Preview don't have to call each other. So when would you choose that extra object over our two direct calls? I'd keep our small function here. But if Preview asks Counter for counts, and Counter tells Preview when to refresh, I'd be chasing the handoff through both components. A mediator gathers those calls in one place. An Observer notification can trigger it; that object still owns the required order and passes the count.

7:59 Let's check the repair. Preview is closing, and Counter must stay active. Can we disconnect Preview and still leave Counter running? Remove that callback, then close the view. Counter remains subscribed, so the next edit reaches it. We also know what our error policy does if another callback fails. Before adding another subscriber, I'd check three things. First, who creates each subscription and removes it? Second, what happens when a callback fails? Third, are the recipients independent, or does a coordinator need to pass a required result?

8:31 Then test the closed view, the failing callback and both registration orders. Observer can let recipients change without teaching the publisher each class. We still own the subscription lifetime and the behavior of those calls. Thanks for listening to Learning Podcasts.