Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adapter

Intent

Let a client written against one interface reuse a class built for a different interface by placing a translator between them, so neither side needs rewriting.

Motivation

A report sender knows a single step: print(doc). The office printer, however, is an older model that only understands old_print(text) with its own setup quirks. Rewriting the sender for one machine is wasteful, and replacing a working printer is expensive. An adapter offers the print(doc) shape the sender expects and forwards each call to the legacy machine in the form it understands, so the new code and the old device cooperate.

Structure

flowchart LR
  Client --> Target
  Target --> Adapter[Adapter]
  Adapter --> Adaptee[Adaptee]
  • Client — the report sender; only knows the print(doc) shape.
  • Target — the print(doc) contract the client depends on.
  • Adapter — implements the target contract and translates each call for the old device.
  • Adaptee — the legacy printer with the mismatched old_print(text) step.

Consequences

  • Benefit: existing, tested code gets reused through a new interface without editing either side.
  • Cost / trade-off: one more layer to follow when debugging; translating awkward mismatches can add noticeable overhead or complexity.

Basic Recap

Adapter exposes the interface a client expects while translating calls and data to an incompatible collaborator. It allows existing code and a legacy or vendor component to cooperate without changing either one’s core model. Translation can include parameter shapes, error categories, and protocol details, but the client-facing contract must remain meaningful. An adapter is a boundary, not a new home for unrelated business workflow.

Complex Scenario

A warehouse fulfillment service reserves stock through a small InventoryPort, but an acquired warehouse only offers a legacy SOAP client with compound keys and numeric status codes. An InventoryAdapter converts the reservation command, adds correlation metadata, invokes the client, and maps its reply into a domain result. The fulfillment service continues to speak in stock units and reservation identifiers. Vendor-specific throttling and XML remain confined to the boundary.

Edge cases

  • Retries: A timeout may occur after the legacy system reserved stock; retry logic must send the same correlation key and query ambiguous outcomes before issuing another reservation.
  • Partial failure: A reply containing accepted and rejected lines must not be flattened into one success boolean; the port needs an explicit partial result.
  • Ordering: Status codes and line numbers may arrive out of request order, so results should be matched by stable line identifiers rather than list position.

The adapter may translate failure semantics, but it should not silently invent strong guarantees the legacy API cannot provide.

Sketch (illustrative pseudocode, not runnable):

InventoryAdapter.reserve(command):
    legacyRequest = toLegacyLines(command)
    legacyRequest.correlation = command.reservationKey

    reply = legacyClient.reserveOrQuery(legacyRequest)
    if reply.outcome == UNKNOWN:
        return ReservationPending(command.reservationKey)

    return ReservationResult(
        accepted = mapByLineId(reply.accepted),
        rejected = mapByLineId(reply.rejected),
        reservationKey = command.reservationKey
    )

When to Use / When Not to Use

Use when:

  • A working class has the behavior you need but speaks a different interface than your client expects.
  • You want to isolate third-party or legacy quirks behind your own interface.

Avoid when:

  • Both sides are new and yours to design — agree on one interface instead of planning an adapter.
  • The mismatch is behavioral, not just spelling — a translator cannot fix different meanings.

Examples

Links to runnable code (same scenario, four languages):

  • examples/elixir/adapter/
  • examples/dart/adapter/
  • examples/go/adapter/
  • examples/rust/adapter/

Expected outcome: printing one document through the adapter shows the client call plus the legacy printer receiving it.

Anti-pattern / Failure Mode

  • Misuse: Wrapping everything in adapters instead of fixing the contract once.

  • Review signal: Chains of adapters translating between adapters.

  • Misuse symptom: The adapter grows allocation rules, pricing decisions, and orchestration for several systems until fulfillment behavior can only be understood by reading vendor translation code. Another misuse is adapting an interface mechanically while leaking its exceptions and sentinel values.

  • Review signal: Look for domain services importing legacy types, adapter methods with many unrelated responsibilities, or callers catching SOAP faults directly. Tests should include ambiguous replies and partial results; a suite that only verifies one-to-one field mapping misses the risky part of the seam.

  • Facade — fit an old interface vs simplify a subsystem.
  • Proxy — different interface vs same interface with control.
  • Postel’s Law — tolerant readers pair well with adapters.

Exercise

Add a second legacy device whose step is fax(number, text). Wrap it in a new adapter behind the same print(doc) contract (send to a fixed number) without touching the client. Both adapters must print their two lines.

Self-check

  • Who owns the translation?
    AnswerThe adapter — the client keeps its interface and the adaptee keeps its implementation.
  • Adapter vs rewriting the old class: what changed?
    AnswerThe old class stays untouched; compatibility logic lives in a separate, replaceable unit.
  • When is an adapter the wrong fix?
    AnswerWhen the two sides mean different things by the call — translation only bridges shape, not semantics.