Ch.4: Design Patterns: Why Decorator Order Matters

Outline

Transcript

0:00 Decorator order can cause a logging bug by hiding denied requests. A Decorator adds behavior around an object's operation; a Proxy controls access. Both can be wrappers: objects holding another object and offering its operation. We'll build both around a report exporter and trace success and refusal. That shows how the logging wrapper can observe denied attempts without changing the editor's call. Imagine our logging wrapper must record the start and end of every editor request, including refusals.

0:29 In the bottom arrangement, access refuses before that wrapper starts. Swap the order, and logging sees the attempt. Both requests are refused; neither reaches the real exporter. The two traces show different coverage. The refusal matches, but what gets observed doesn't. Let's build the objects behind those rows. First, take a report titled Roadmap. Our fictional exporter formats text in memory and returns the result shown here. There's no file or network request hiding in this example. Let's use the list to watch this call.

0:59 The export entry comes from the formatter. Later, the log and access labels show which wrapper ran. The editor function asks its exporter for that operation and passes the report back. The call stays the same when the object changes. If we give the editor a logging object instead, does it need a different kind of export call? No. Keep that same call. The new object must offer it too, then pass the work along to the formatter. Then when we create Logging Exporter, have we already started an export, or just connected the objects?

1:33 Just connected them. The constructor stores inner, a reference to the next object, and events, the shared list. We're adding logging without rewriting the exporter, as Refactoring Guru's Decorator tutorial explains. That source is linked in the description. I like being able to follow the connection. But does the final log happen only if the inner call works? Now follow that logging method. It records its start, calls the inner export operation, then runs finally on the way out. On success, the report text passes back through the wrapper.

2:06 So the event order is start, the real export, then end. That return inside try doesn't skip finally. Python's language reference includes cleanup on the way out of a return. Now suppose the formatter raises an error instead of producing text. An exception is that error traveling back to the caller. The final logging line still runs here. Oh, then log end can't mean export succeeded. I was about to give that label rather more credit than it earned. It only tells us the logging wrapper finished. Exactly. This wrapper doesn't catch or replace the error.

2:40 After finally, the same error continues outward. Our test checks that as well as the successful result. With the same held-object relationship, Access Proxy offers export too, but its job is deciding whether the underlying service may be reached. That's the Proxy intent: stand in for the service while controlling access to it. For example, our application setup supplies an allowed decision. If it's false, the first branch records denial, then raises Permission Error. The method stops before calling its inner object.

3:11 If access is allowed, the last lines record that decision and delegate. The editor still supplies only the title. It doesn't send a permission flag with its export request. But are we actually verifying anyone's permissions here? Here we're supplying a decision to trace the code. We aren't verifying a user's permissions. A real application needs that check; calling the class Proxy doesn't provide it. Those access entries are its own logging. A Proxy can log too; the access-control job is what gives this one its name.

3:43 Now follow the assignments down the screen. Start with the list and base exporter. Access holds base, then outer holds access. The editor receives that outer logging object. The editor enters logging first, so start appears. Then logging delegates to the proxy. The proxy records denial and raises the error before any formatting happens. We're coming back out with an error now. Which line in the logging wrapper still has to run? Its finally block. That's the third event, log end. Then Permission Error leaves logging.

4:15 There isn't a report result, and the export event never appears. The logging wrapper observes this refused request even though the real operation never starts. It surrounds the access check as well as the formatter. Build a fresh case with the same classes and denied decision, but reverse their order. This time outer is Access Proxy. Which logging lines execute? Neither. Access Proxy refuses before it calls its inner object, now Logging Exporter. We never enter the logging method, so even its finally block has nothing to finish.

4:47 Right, finally isn't running in every object nearby. It belongs to a call we actually entered. The trace contains access denied and stops there. Compare the rows. Both prevent the base export. Logging outside includes refused requests; access outside only lets allowed attempts enter logging. We didn't change either class. My first thought was to put permission checking first because it sounds safer. But that also chooses what the logging wrapper gets to see. That safety instinct still holds: neither order permits denied exports.

5:19 Now allow the request. In the top row, logging starts before the access decision. In the bottom row, access is allowed before logging starts. Both then reach the formatter, finish logging and return the same report text to the caller. I'd be tempted to check the returned report and stop there. The denied trace would catch the ordering mistake. For our all-attempt requirement, the logger must be entered first. Access outside fits a different requirement: start logging only after permission is granted.

5:50 But keeping the editor call unchanged doesn't make the wrapper the original object. Back to logging outside: look at the three references and their identity checks. In Python, is asks whether they're the same object. Outer isn't base. Outer holds access, and access holds base. The editor uses the same operation without holding the original exporter. Now imagine another caller still has that base reference. What happens if it calls export directly, even while the proxy's decision is denied? The base exporter runs.

6:20 It knows nothing about the wrapper's permission check. That direct arrow bypasses both wrappers, and our trace contains only export. Then drawing a gate hasn't proved that every caller goes through it. Trusted setup needs to assemble the intended route and control which references the relevant callers receive. And controlling those references may not be enough to enforce access. This wrapper only checks calls that reach it. But for this small feature, I think I'd keep the fixed policy in one function.

6:49 The workflow on screen starts logging, checks access, exports if allowed, then finishes logging. I'd choose that too for one fixed combination. The tested function has the same logging-outside behavior, including finally. Separate objects would add names and connections we don't yet need. Suppose the preview tool needs logging alone, while the shared editor needs logging and access checking. Both use the same export operation. Would you keep that fixed design? I'd consider wrappers for those callers.

7:20 Reuse the logger in both, then add access inside it for the shared editor. Neither caller needs a new operation. A different formatter could already go into our function. It's the different required combinations that would justify these objects. Then take our original requirement: the logging wrapper must record the start and end of denied editor requests. Which order lets it do that? So logging goes outside Access Proxy. Start happens before the permission decision, finally records the end, and Permission Error still reaches the editor.

7:51 We record the attempt without running the formatter. Before choosing, I'd ask three things. First, what behavior or access promise is needed? Second, what happens on success and failure in this order? Third, who gets the wrapper, and who still has the base? Then I'd test a caller holding base, too. A suitable order doesn't prevent that bypass. Decorator adds behavior, Proxy controls access, and we need to check which object each caller receives. Keep the order in the test, alongside the returned result.

8:22 Thanks for listening to Learning Podcasts.