Skip to content

    Frontend System Design

    Command, Strategy, Adapter and Facade

    Four patterns for front-end code: commands as logged data, strategies as functions, adapters at the edge and a checkout facade, and when each earns its place.

    By Published 12 min read

    • frontend-system-design
    • design-patterns
    • adapter
    • facade
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Design Patterns for Front Ends

    What you'll learn: By the end of this lesson you will be able to turn a user action into a command object that can be logged, queued, undone and replayed, use a strategy as an ordinary function to swap an algorithm, write an adapter that makes a third-party SDK or a legacy response fit your own interface, put a use case behind a small facade, and say for each of the four what problem it solves, what it costs, and when a plain function is enough.

    Think of a restaurant trip. The waiter writes your order on a slip: that slip is a command, a request turned into a thing that can be queued, passed to the kitchen, cancelled or reprinted. You choose how the food reaches you, delivery by bike or by van, and the restaurant does not care which: that is a strategy. Your phone charger does not fit the foreign wall socket, so you carry a travel plug: an adapter. And in a hotel you ask the concierge to "arrange a dinner and a taxi" without knowing which kitchen and which taxi firm are involved: a facade.

    These four come from the object-oriented design-pattern catalogue. In a front end they are usually lighter than the textbook class diagrams, because JavaScript has functions as values. The running example is the cart and checkout of the ShopStream storefront used in this course; all prices, thresholds and delays in the lab are illustrative values.

    The core idea

    1. Command: a request turned into a stand-alone object that contains all information about it (Refactoring.Guru's catalogue), so it can be passed, delayed, queued and undone.
    2. Strategy: a family of interchangeable algorithms behind one interface; in TypeScript, usually one function type.
    3. Adapter: lets objects with incompatible interfaces collaborate.
    4. Facade: a simplified interface to a complex set of classes.

    Command: the request as data

    A click handler that calls cart.add(sku) directly has done the work and left no trace. A command separates what was asked from who does it and when. The lab's cart has three command types (addItem, removeItem, applyVoucher), each a plain object. A registry maps each type to a handler that returns the next state or a reason for refusing, and a bus dispatches commands and keeps a log.

    Figure 1. A command bus

    Commands are data; the bus looks up the handler, logs, and can undo, queue or replayUI to Command bus (command object); Command bus to Handlers (lookup by type); Handlers to Cart state (result)UI: invokerUIinvokerCommand bus: log, undo, queueCommand buslog, undo, queueHandlers: one per command typeHandlersone per commandtypeCart state: next state or refusalCart statenext state orrefusalcommand objectlookup by typeresult

    How to read this: the UI never calls a handler. It hands over a command, so the same object can be stored, sent elsewhere or replayed later.

    Illustration 1: the minimal example

    Five commands go through a bus: two are refused, one is undone, and the applied ones are exported as JSON and replayed on a fresh bus. Two more are queued and flushed.

    Expected output, captured from a real run (Node 26.13.1, node src/demo.ts in examples/frontend/labs/command-strategy-adapter-facade):

    === 1. command: commands are data, so they can be logged, undone and replayed
    #1 applied  {"type":"addItem","sku":"tea","qty":2}
    #2 rejected {"type":"addItem","sku":"tea","qty":0}  (quantity must be a whole number of at least 1)
    #3 applied  {"type":"applyVoucher","code":"WELCOME5"}
    #4 rejected {"type":"removeItem","sku":"coffee"}  (coffee is not in the cart)
    #5 applied  {"type":"addItem","sku":"coffee","qty":1}
    state: {"lines":[{"sku":"tea","qty":2},{"sku":"coffee","qty":1}],"voucher":"WELCOME5"}
    after undo: {"lines":[{"sku":"tea","qty":2}],"voucher":"WELCOME5"}
    stored: [{"type":"addItem","sku":"tea","qty":2},{"type":"applyVoucher","code":"WELCOME5"},{"type":"addItem","sku":"coffee","qty":1}]
    replayed on a fresh bus: {"lines":[{"sku":"tea","qty":2},{"sku":"coffee","qty":1}],"voucher":"WELCOME5"}
    queued: 2, lines before flush: 0
    queued: 0, state after flush: {"lines":[{"sku":"tea","qty":2}],"voucher":null}

    Rejected commands are in the log with a reason and change nothing. Undo restores the snapshot taken before the last applied command (the catalogue notes undo can restore saved state or run an inverse operation; this lab does the first). The stored JSON replays to the same state, which is only possible because a command is data. Queued commands do nothing until the flush, the shape of "keep these while offline, send later". A later lesson in this module, on undo, redo and event sourcing, builds a full history on the same idea.

    Commands and events. The Redux style guide recommends treating actions as events that occurred rather than setters, because that gives more meaningful names, fewer dispatches and a more useful log. A command says what the user wants, the handler may refuse, and the log records the decision; decide on purpose which style each name follows.

    A platform example. MDN's Invoker Commands API lets a button declare, with commandfor and command attributes, an action on another element, and fires a command event whose command property names the action; custom names start with --. At the time of writing MDN shows it as Baseline 2025, newly available since December 2025, so check compatibility first.

    Strategy: the algorithm as a function

    If a function picks its behaviour with a growing if or switch on a mode string, the variants are strategies waiting to be named. Refactoring.Guru lists replacing a massive conditional among variants of one algorithm as a use, and notes that in languages with functional support anonymous functions can do the job with less code. So in TypeScript a strategy is a type:

    export type ShippingStrategy = (cart: PricedCart) => Cents;

    The lab has three shipping strategies, three sort comparators and two backoff strategies. The platform's own example is the compare function of Array.prototype.sort: MDN says a negative result puts a before b, a positive one after, and zero or NaN means equal; the sort works in place and is stable since ES2019. The lab's sortProducts copies the array first because of the in-place behaviour.

    Illustration 2: the realistic example, strategies in a checkout

    The checkout picks a shipping strategy by name, and the catalogue a sort order by name.

    Expected output, captured from a real run (scenarios 2 and 3):

    === 2. strategy: shipping cost by name (illustrative prices, in cents)
    subtotal 3000, 2 items: standard=499  express=1299  pickup=0
    subtotal 6000, 5 items: standard=0  express=1499  pickup=0
    pickShipping("drone"): {"ok":false,"reason":"unknown shipping option drone"}
    
    === 3. strategy: sorting with a comparator, and backoff delays as data
    price-asc  Tea, Cocoa, Coffee
    price-desc Coffee, Cocoa, Tea
    rating     Coffee, Tea, Cocoa
    original order kept: Tea, Coffee, Cocoa
    fixed(1000, 3):             [1000, 1000, 1000]
    exponential(500, 4000, 6):  [500, 1000, 2000, 4000, 4000, 4000]

    An unknown name is a refusal with a reason, not a silent fallback to a default price (the lab also rejects inherited names such as toString with Object.hasOwn). And the backoff strategies are data: delaysOf returns the whole list of waits, so a test checks the policy without sleeping.

    Strategy is not State. Refactoring.Guru says State can be seen as an extension of Strategy: strategies are independent and unaware of each other, while states may know about each other and change the context's state. If the next choice depends on what happened last, you want a state machine; see Finite State Machines for UI.

    Adapter: fit it at the edge

    Refactoring.Guru distinguishes an object adapter (composition: it implements the client interface and wraps a service object) from a class adapter (inheritance, needing multiple inheritance). In TypeScript you almost always write the first.

    The lab has two service adapters. The app depends on its own Analytics port, track(event). Two invented vendor SDKs (not any real product's API) differ: A takes a name and string-only parameters; B takes an object with a Title Case name, a total in currency units and a timestamp. One adapter wraps each.

    Figure 2. Two vendors behind one port

    The app calls its own Analytics port; each adapter translates for one vendor SDKApp code to Adapter A (same call); App code to Adapter B (same call); Adapter A to Vendor A SDK; Adapter B to Vendor B SDKApp code: track(event)App codetrack(event)Adapter A: strings onlyAdapter Astrings onlyAdapter B: Title Case, unitsAdapter BTitle Case, unitsVendor A SDK: logEvent(name, params)Vendor A SDKlogEvent(name,params)Vendor B SDK: send(payload)Vendor B SDKsend(payload)same callsame call

    How to read this: swapping or adding a vendor changes one box on the right and nothing on the left. The port is the app's interface, not either vendor's. The same idea at application scale is in Ports and Adapters in the Front End.

    A data adapter, fromLegacy, turns a legacy response (prod_id, price_cents, in_stock: "Y") into the app's product type and throws an AdapterError for bad data, so a malformed response fails at the edge, not inside a component.

    Expected output, captured from a real run (scenario 4):

    === 4. adapter: one event, two incompatible vendor SDKs
    vendor A received: [{"name":"product_viewed","params":{"sku":"tea"}},{"name":"order_placed","params":{"orderId":"o-1","totalCents":"1998"}}]
    vendor B received: [{"event":"Product Viewed","properties":{"sku":"tea"},"sentAt":1700000000000},{"event":"Order Placed","properties":{"orderId":"o-1","total":19.98},"sentAt":1700000000000}]
    legacy -> domain: {"sku":"tea","title":"Tea","cents":450,"inStock":true}
    bad legacy data: AdapterError: price_cents must be a non-negative integer

    Adapter B takes now as a parameter, so the timestamp is fixed in tests. One contract test runs against every analytics adapter (one SDK call per event, no throw), which keeps a third adapter honest. The cost, per the catalogue, is more interfaces, and sometimes it is simpler to change the service itself, which you cannot do with a vendor's SDK.

    Facade: one entry point for a use case

    A checkout touches the cart, prices, shipping, payment and analytics. Without a facade each screen calls all five in the right order. Refactoring.Guru warns of the main risk of a facade: it can become a god object coupled to all classes of an app.

    The lab's CheckoutFacade has one method, placeOrder(request): cart commands, prices, shipping strategy, one charge, then analytics. It returns one result that names the stage where it stopped.

    Figure 3. A call that stops at the first failing stage

    sequenceDiagram accTitle: The checkout facade stages accDescr: The screen calls placeOrder once. The facade dispatches cart commands, then prices the lines, then picks a shipping strategy by name, then charges the card once, then reports to analytics. A failure in the first four stages returns a result naming the stage and nothing after it runs. A failure in analytics becomes a warning on a successful result. participant S as Screen participant F as CheckoutFacade participant C as Cart commands participant P as Payment participant A as Analytics S->>F: placeOrder(request) F->>C: addItem, applyVoucher F->>F: price lines, pick shipping F->>P: charge(total, orderId) once F->>A: track(order_placed) F-->>S: ok result, or the failing stage

    How to read this: the order of the steps and the rule about analytics live in one place. The screen sees one call and one result shape.

    Illustration 3: the failure example

    Expected output, captured from a real run (scenario 5):

    === 5. facade: one call, five steps, and where it stops
    happy path        {"ok":true,"orderId":"o-1","subtotalCents":1800,"discountCents":500,"shippingCents":499,"totalCents":1799,"warnings":[]}
    bad quantity      {"ok":false,"stage":"cart","reason":"quantity must be a whole number of at least 1"}
    unknown shipping  {"ok":false,"stage":"shipping","reason":"unknown shipping option drone"}
    card declined     {"ok":false,"stage":"payment","reason":"card declined"}
    analytics down    {"ok":true,"orderId":"o-1","subtotalCents":450,"discountCents":0,"shippingCents":0,"totalCents":450,"warnings":["analytics failed"]}
    subsystem calls made: ["charge 1799 o-1","analytics order_placed","charge 450 o-1"]

    The last rows are the point. A declined card stops at payment, and the call list shows no analytics event for it. A failing analytics vendor does not fail the order: the card was charged, so the facade returns success with a warning, and no screen can get that rule wrong. A second use case gets a second method; when the class needs to know everything, split it.

    Facade or adapter? A facade defines a new interface for existing objects; an adapter makes an existing interface usable, and usually wraps one object where a facade works with a whole subsystem. The checkout facade uses the analytics adapter: they stack.

    Trade-offs

    Pattern Gain Cost Plain alternative
    Command Log, undo, replay, queue; refusal with a reason A layer and a registry A direct function call
    Strategy Swap behaviour; test policies as data The caller must choose; few variants may not justify it A lookup object of functions
    Adapter Vendor details stay at the edge An interface per boundary; contract tests Change the code you own
    Facade One place for order and failure rules Can become a god object A helper function

    If behaviour depends on the previous event, use a state machine instead of a strategy.

    Build it

    Goal. Run the four patterns on a cart and checkout, and read what each leaves in the output.

    Setup. The lab is in the course's example workspace (Node 26.13.1), pure TypeScript with no DOM, no network and no timers.

    cd examples/frontend/labs/command-strategy-adapter-facade
    ../../node_modules/.bin/vitest run    # 35 tests
    ../../node_modules/.bin/tsc -p tsconfig.json
    node src/demo.ts                      # golden: examples/frontend/golden/command-strategy-adapter-facade.txt

    Steps. Run the tests and the demo and compare it with the outputs above. In src/command.ts find why a rejected command is not pushed onto the undo stack; in src/facade.ts find the try/catch around analytics.

    Verified. The 35 tests passed with Vitest 5.1.0 and the type check (TypeScript 7.0.2) passed. The demo was run twice with identical output, and it is the golden file the outputs above were taken from. The two vendor SDKs and the payment service are fakes written for the lab; nothing was run against a real vendor, a browser or React.

    Break it. In test/patterns.test.ts, the test "a failing analytics vendor never fails the order; it becomes a warning" expects ok: true. Change the expectation to ok: false and the test fails, because the facade swallows the analytics error. Change it back.

    In practice: switching analytics vendors during a checkout redesign

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The storefront calls its analytics SDK from about forty places, including the checkout button handler. The company is moving to a second vendor and wants both running side by side for a month (illustrative).

    Starting architecture

    Figure 4. Vendor calls in every component

    Starting architecture: components call the vendor SDK directlyProduct page to Vendor SDK; Checkout to Vendor SDKProduct page: calls SDKProduct pagecalls SDKCheckout: calls SDK, chargesCheckoutcalls SDK,chargesVendor SDK: its own shapeVendor SDKits own shape

    How to read this: the warning boxes know the vendor's shape. A second vendor means touching every call site, and an SDK that throws in the checkout handler can fail the order.

    Options considered

    Option What it fixes What it costs Risk
    Find and replace calls Nothing structural Forty edits, twice Drift
    A port with one adapter per vendor Both vendors, one call shape Two adapters, a contract test Port shaped by vendor one
    A checkout facade over the port Fixed order, named failures One more class God object

    The decision

    Field Decision record
    Context Vendor shapes are spread over the code, and analytics can fail the order.
    Decision Define an Analytics port of the app's own events. Write one adapter per vendor and fan out to both during the overlap. Put the checkout steps in a facade that treats analytics as best effort and names the failing stage.
    Consequences, good Removing a vendor deletes one adapter. Checkout rules live in one tested place.
    Consequences, bad Event names are now the app's contract and need owners.
    Revisit when A third use case makes the facade need to know everything.

    Rollout and verification

    1. Write the contract test first and run it against each adapter.
    2. Move call sites one screen at a time, checkout first.
    3. Compare the two vendors' counts for a few days; a gap is a bug in an adapter.
    4. Test the facade stages with fake payment and analytics, including a declined card and a throwing vendor.

    The 2 a.m. failure

    The new vendor's script is blocked for a share of visitors, and its SDK object is missing. Orders are charged but the customer sees an error page, because the code that called track threw after the payment and the component treated it as a failed order.

    First three checks: (1) look at where the exception surfaced relative to the payment call; (2) check whether track is called inside the same try as the charge; (3) check whether the adapter assumes the SDK exists. Mitigation: catch around track and report a warning, as the lab's facade does. Follow-up: a test with an analytics fake that throws, and a rule that analytics calls are never on the critical path of a payment.

    Architect's notes

    • Name what varies first: the request, the algorithm, the interface or the number of calls.
    • Keep commands as plain data so they serialise; behaviour lives in handlers.
    • Prefer a function type to a strategy class until a strategy needs state.
    • Adapt at the boundary, keep the port in your own words, and test every adapter against one contract.
    • Give a facade one method per use case and a result that names where it stopped.

    Common mistakes

    • A command with logic inside it, so it cannot be replayed elsewhere.
    • A silent default for an unknown strategy name, hiding a typo as a wrong price.
    • An adapter that leaks the vendor's types into the app.
    • A facade with a method for every screen, which becomes a god object.
    • A strategy that needs the previous result: a state machine in disguise.
    • Sorting a shared array in place with a comparator.

    Key takeaways

    • A command is a request as data: loggable, queueable, replayable, and able to be refused with a reason.
    • A strategy is an interchangeable algorithm; in TypeScript it is usually a function type.
    • An adapter converts at the edge so vendor shapes do not spread; test adapters with a shared contract.
    • A facade gives one entry point per use case and a place for order and failure rules; keep it small.
    • Strategy varies an algorithm; State changes behaviour based on history; do not confuse them.
    • Use the plain alternative when there is one variant and one caller.

    Practice exercises

    Exercise 1: Starter (30 min). Add a clearCart command to the lab with a handler and a test, and decide whether undo should restore the lines.

    Exercise 2: Intermediate (2 hours). Add a fourth shipping strategy, locker, and a test that an unknown name is still refused. Then explain why pickShipping uses Object.hasOwn.

    Exercise 3: Advanced (half day). Write a third analytics adapter whose SDK sends asynchronously and can fail. Decide what track returns, update the contract test, and describe how the facade should treat a rejected promise.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments