Explore
WEBSTER / SOFTWARE ENGINEERING← Senior DeveloperEducational reference · continually evolving

Chapter 11 / 15 · Webster International

Design Patterns: The Practical Catalogue

Learn the problem and trade-off behind creational, structural, behavioural and application-level patterns—with realistic code and failure cases.

← Complete index

The big idea

A design pattern is a named, reusable approach to a recurring problem, not a rule that every project must follow. Start with the problem; add a pattern only when it makes intent clearer.

01 / FIELD NOTE

Recognising patterns without overengineering

Classic object-oriented patterns fall into creational (creating objects), structural (composing objects) and behavioural (sharing responsibilities). Modern systems also use architectural patterns such as repository, outbox, CQRS and pub/sub.

Why it matters

A shared vocabulary speeds conversations, but forcing patterns onto trivial problems adds indirection.

In practice

Before creating a Factory, ask whether a two-line function solves the real need. Before inventing Singleton, ask whether ordinary dependency injection makes ownership clearer.

Pattern-by-pattern field guide

Start with a change pressure: which responsibility varies, who owns state, and what failed in the current design? Pattern names describe the remedy, not the goal. A small function is often the right abstraction.

Composition first

Compose independently testable behaviours instead of creating a subclass for every feature combination.

Example: CRM event formatting can be assembled from formatting, locale and permission functions.

Trade-off: Avoid a compositional framework if one plain function expresses the complete rule.

JavaScript example · Composition first
const renderEvent = (event, formatDate, canEdit) => ({
  label: formatDate(event.startsAt) + ' · ' + event.title,
  editable: canEdit(event)
});

Choose by failure mode

Match change or failure pressure to a pattern: provider churn suggests Adapter; unpredictable latency suggests timeout/bulkhead; reversible UI actions suggest Command.

Example: Before refactoring bookings, write down whether the actual defect is duplication, coupling, invalid state, or poor observability.

Trade-off: Do not add a message broker just to avoid calling one well-scoped function.

JavaScript example · Choose by failure mode
function choose(problem) {
  return ({providerMismatch:'Adapter', variableAlgorithm:'Strategy',
    multiStepUndo:'Command', unreliableRemote:'Timeout + Retry'})[problem] ?? 'Keep it simple';
}
Try it: For an existing feature, write the single change pressure and compare a two-function solution to one named pattern.

Verify: You can describe which dependency or failure is isolated, and name what complexity the solution adds.

02 / FIELD NOTE

Factory Method and Abstract Factory

Factory Method delegates which implementation to create; Abstract Factory produces related families of compatible objects. They hide concrete classes from code that needs an interface.

Why it matters

Products can switch providers without scattering constructors and provider-specific details throughout the application.

In practice

A report factory creates HTML or PDF report exporters; an abstract factory supplies matching cloud storage and queue adapters per environment.

JavaScript
function makeNotifier(kind) {
  if (kind === 'email') return {send: sendEmail};
  if (kind === 'sms') return {send: sendSms};
  throw new Error('Unknown notifier');
}
// Simple factory function; Factory Method is the OO pattern.

Pattern-by-pattern field guide

Creation patterns vary how objects come into existence. A simple conditional factory is not the same as GoF Factory Method, which lets a specialised creator supply a product while the surrounding workflow stays unchanged.

Factory Method

A base workflow calls an overridable creation method and handles the resulting product through a stable contract.

Example: A report pipeline can render every document the same way while each report subclass chooses the exporter.

Trade-off: Skip the inheritance-based pattern when an injected function or small factory is clearer.

JavaScript example · Factory Method
class ReportJob {
  createExporter() { throw new Error('Override me'); }
  async run(rows) { return this.createExporter().export(rows); }
}
class CsvJob extends ReportJob {
  createExporter() { return {export: rows => rows.map(r => r.join(',')).join('\n')}; }
}

Abstract Factory

Construct a family of compatible implementations together; the consuming workflow never needs to mix incompatible environments or providers.

Example: A tenant deployment receives a matching storage adapter and event queue from one provider family.

Trade-off: A configuration object with two fields may be enough when no family varies.

JavaScript example · Abstract Factory
const providers = {
  local: () => ({storage: new Map(), queue: []}),
  test: () => ({storage: new Map(), queue: []})
};
function createInfrastructure(kind) {
  const make = providers[kind];
  if (!make) throw new Error('Unsupported provider');
  return make();
}

Simple factory (contrast)

A standalone function picks a concrete product. Useful, but distinct from the two GoF patterns above.

Example: Choose an email or SMS sender for one notification job.

Trade-off: Do not make a subclass hierarchy just to switch on a constant.

JavaScript example · Simple factory (contrast)
function notifier(channel, deps) {
  if (channel === 'email') return deps.email;
  if (channel === 'sms') return deps.sms;
  throw new Error('Unknown channel');
}
Try it: Implement a Creator hook and compare it with an injected factory function.

Verify: Adding a PDF exporter does not alter the common report-processing workflow.

03 / FIELD NOTE

Builder, Prototype and Singleton

Builder constructs complex objects step by step; Prototype copies an existing configured object; Singleton limits an object to one instance for a defined scope. In JS modules, modules themselves can provide controlled shared instances.

Why it matters

These address different lifecycle problems: configuration clarity, cloning and shared state.

In practice

Use Builder for a complex validated report definition; clone a known template for a new campaign; scope one application config instance at startup.

Pattern-by-pattern field guide

These solve different construction questions: validated incremental assembly, copying a configured starting point, and controlling how many shared instances exist.

Builder

Collect options in readable steps, then validate cross-field rules at build time.

Example: A recurring booking needs a client, recurrence window, capacity and pricing policy before it can be saved.

Trade-off: Do not create builders for immutable objects with just two required arguments.

JavaScript example · Builder
class BookingBuilder {
  constructor() { this.data = {}; }
  client(id) { this.data.clientId = id; return this; }
  starts(iso) { this.data.startsAt = iso; return this; }
  build() {
    if (!this.data.clientId || !this.data.startsAt) throw Error('Missing booking fields');
    return Object.freeze({...this.data});
  }
}

Prototype

Copy a known configuration then deliberately override unique or nested values.

Example: Clone an event template to create a new week's rehearsal, with a new ID and start time.

Trade-off: A shallow spread copies nested references; choose structuredClone only for supported structured data.

JavaScript example · Prototype
const template = {durationMinutes:60, tags:['music'], published:false};
const event = {...structuredClone(template), id:crypto.randomUUID(),
  startsAt:'2026-11-02T18:00:00-05:00'};

Singleton (scoped)

Reuse one instance per intended scope—often per application process or request container, not per global tenant population.

Example: Load configuration once during a process boot, then inject the immutable result.

Trade-off: Global mutable state leaks between tests and tenants; one process-wide instance does not mean distributed uniqueness.

JavaScript example · Singleton (scoped)
function createApp(config) {
  const settings = Object.freeze({...config});
  return {schedule: createScheduler(settings)};
}
// One app container per deployment, not one mutable global for all users.
Try it: Build a validated booking, clone a template without sharing a nested tags array, and scope a config per test.

Verify: Invalid bookings throw, clones are independent, and one test never changes another's settings.

04 / FIELD NOTE

Adapter, Facade and Proxy

Adapter translates one interface into another; Facade simplifies a complicated subsystem behind a focused API; Proxy controls access or adds behaviour around an existing dependency.

Why it matters

Third-party integration quirks should not infect the whole domain model.

In practice

Wrap two ticketing providers in getAvailableEvents(); expose a CheckoutFacade to orchestrate inventory and payment; use a proxy to add cache and access checks.

JavaScript
const adapter = provider => ({
  async findEvents(town) {
    const raw = await provider.search({place: town});
    return raw.items.map(x => ({id: x.uid, title: x.name}));
  }
});

Pattern-by-pattern field guide

All three sit at a boundary but for different reasons: translate a contract, simplify an operation, or control access to an existing subject.

Adapter

Translate incompatible data shapes and errors into one domain contract.

Example: Two ticket vendors return different venue ID and date field names; the CRM reads a common Event type.

Trade-off: Do not quietly discard timezone or currency details needed by the business.

JavaScript example · Adapter
function venueAdapter(provider) {
  return {async list(town) {
    const rows = await provider.query({place:town});
    return rows.items.map(x => ({id:String(x.uid), title:x.name, startsAt:x.startISO}));
  }};
}

Facade

Expose a narrow orchestration API over several collaborators.

Example: A booking facade validates availability, reserves capacity, writes the booking and requests a receipt.

Trade-off: A facade must not claim atomicity when external operations can fail independently.

JavaScript example · Facade
function bookingFacade({availability, bookings, notify}) {
  return {async create(input) {
    await availability.ensureFree(input);
    const saved = await bookings.insert(input);
    await notify.queueReceipt(saved.id);
    return saved;
  }};
}

Proxy

Preserve an object's interface while enforcing policy, memoizing reads, or adding measurement.

Example: A client-service proxy checks tenant membership before returning personally identifying records.

Trade-off: Caching sensitive results without tenant-aware keys creates data exposure.

JavaScript example · Proxy
const privateClientProxy = (repo, authorize) => ({
  async get(tenantId, clientId, actor) {
    await authorize(actor, tenantId, 'client:read');
    return repo.get(tenantId, clientId);
  }
});
Try it: Wrap two different provider payloads, then put a permission-checking proxy in front of client reads.

Verify: Consumers see one data shape and unauthorized tenant reads fail before persistence access.

05 / FIELD NOTE

Decorator, Composite, Bridge and Flyweight

Decorator wraps behaviour such as retry or instrumentation; Composite treats a collection and a single item through the same interface; Bridge separates abstraction from its implementation; Flyweight shares repeated immutable information.

Why it matters

These patterns manage combinations without a subclass for every possibility.

In practice

A logged storage adapter decorates a plain storage interface; a nested navigation uses Composite; a drawing tool selects independent renderer implementations.

Pattern-by-pattern field guide

Structural patterns tame combinations: Decorator adds orthogonal behaviour; Composite treats trees uniformly; Bridge varies two dimensions independently; Flyweight shares immutable repeat data.

Decorator

Wrap one implementation with another object preserving its contract.

Example: Instrument a queue publisher without changing how business logic calls publish.

Trade-off: A decorator should rethrow failures and avoid exposing secrets in logs.

JavaScript example · Decorator
const timed = (publisher, metric) => ({
  async publish(event) {
    const start = performance.now();
    try { return await publisher.publish(event); }
    finally { metric.observe('publish_ms',performance.now()-start); }
  }
});

Composite

Use the same operation for an individual item and a nested group.

Example: A navigation tree has links and folders; each contributes visible labels recursively.

Trade-off: Do not represent a simple flat list as a deep tree without a requirement.

JavaScript example · Composite
const link = title => ({labels:()=>[title]});
const group = children => ({labels:()=>children.flatMap(x=>x.labels())});
const nav = group([link('Home'),group([link('CRM'),link('Calendar')])]);

Bridge

Separate two dimensions that can vary without multiplying subclasses.

Example: An invoice's content format (HTML/PDF) and delivery channel (email/download) vary independently.

Trade-off: Two straightforward parameters can be clearer than multiple abstraction layers.

JavaScript example · Bridge
function sendReport(report, renderer, transport) {
  return transport.deliver(renderer.render(report));
}
// Renderer and transport change independently.

Flyweight

Share large immutable properties and keep each item's changing properties outside the shared object.

Example: A map of thousands of bookings shares location icons and style metadata but not event-specific state.

Trade-off: Do not share mutable client data or make a cache immortal without bounds.

JavaScript example · Flyweight
const markerStyle = Object.freeze({shape:'pin',size:18});
const pins = events.map(e=>({lat:e.lat,lng:e.lng,
  style:markerStyle,bookingId:e.id}));
Try it: Compose a folder tree, render it through two output formats, and share frozen marker style records.

Verify: Changing one event never mutates another; decorators propagate failure unmodified.

06 / FIELD NOTE

Strategy and Template Method

Strategy selects one interchangeable algorithm at runtime; Template Method defines a workflow skeleton whose steps vary in subclasses. Strategy often maps more naturally to dependency injection in JavaScript.

Why it matters

Separating a choice from the calling workflow makes behaviour testable.

In practice

ShippingCalculator chooses pickup, standard or express pricing based on an injected strategy; a report generation workflow shares validation and export steps.

JavaScript
const price = {
  pickup: subtotal => subtotal,
  courier: subtotal => subtotal + 799
};
const total = price[mode](subtotalCents);

Pattern-by-pattern field guide

Strategy chooses among interchangeable behaviours through composition; Template Method preserves the order of a shared workflow while allowing a subclass to replace selected steps.

Strategy

Inject one function or object per algorithm instead of mixing selection branches into all callers.

Example: A delivery dispatcher ranks stops by earliest deadline, shortest route, or customer priority.

Trade-off: Optimization is constrained by time windows and capacity; distance alone is not universally optimal.

JavaScript example · Strategy
const rankers = {
  deadline: (a,b)=>a.deadline-b.deadline,
  priority: (a,b)=>b.priority-a.priority
};
function orderStops(stops, algorithm) {
  return [...stops].sort(rankers[algorithm]);
}

Template Method

Fix the processing sequence and delegate specific steps to hooks.

Example: Every import validates, normalizes, persists and audits, while source-specific classes normalize differently.

Trade-off: Prefer a function pipeline in JavaScript if inheritance adds little value.

JavaScript example · Template Method
class ImportJob {
  async run(input) {
    const rows = this.normalize(input);
    if (!rows.length) throw Error('Empty import');
    return this.save(rows);
  }
  normalize() { throw Error('Override normalize'); }
}

Strategy plus dependency injection

Provide algorithms at the composition root so callers do not need to know concrete implementations.

Example: Tests inject a deterministic routing strategy without external services.

Trade-off: Avoid runtime registries with hidden mutable global selectors.

JavaScript example · Strategy plus dependency injection
const makePlanner = rank => stops => [...stops].sort(rank);
const planner = makePlanner((a,b)=>a.windowStart-b.windowStart);
Try it: Implement two delivery ordering algorithms and inject the desired one into the same planner.

Verify: Both produce deterministic, testable output without editing the planner.

07 / FIELD NOTE

Observer, Pub/Sub and Mediator

Observer notifies subscribers of state changes; pub/sub distributes messages across parts of a system, sometimes through a broker; Mediator centralises interactions between cooperating components.

Why it matters

A calendar can react to changes without every widget knowing each other's internal implementation.

In practice

When a filter changes, subscribers update their derived views; on OrderPaid an event bus fans out to fulfilment and analytics.

Pattern-by-pattern field guide

Ask how events move: Observer retains direct subscribers, pub/sub uses a bus or broker boundary, and Mediator centralizes coordination among peers.

Observer

A subject explicitly registers callbacks and announces state changes.

Example: One selected calendar date updates the detail list and map filters.

Trade-off: Always unsubscribe on unmount; listener leaks accumulate through navigation.

JavaScript example · Observer
function createObservable() {
  const listeners=new Set();
  return {subscribe(fn){listeners.add(fn);return ()=>listeners.delete(fn);},
    publish(value){for(const fn of listeners) fn(value);}};
}

Publish/Subscribe

Producers publish events by topic without knowing which consumers handle them; across processes a broker adds delivery concerns.

Example: BookingCreated drives receipt creation, map refresh and analytics.

Trade-off: Delivery may be duplicated, delayed or out of order; consumers need idempotency.

JavaScript example · Publish/Subscribe
function eventBus() {
  const listeners=new Map();
  return {on(topic,fn){const s=listeners.get(topic)||new Set();
      s.add(fn);listeners.set(topic,s);return ()=>s.delete(fn);},
    emit(topic,payload){for(const fn of listeners.get(topic)||[])fn(payload);}};
}

Mediator

One coordinator owns cross-component interaction rules, reducing references among participating widgets.

Example: The map, calendar and client selector communicate through a shared controller.

Trade-off: A mediator that handles everything can become a God object.

JavaScript example · Mediator
function dashboardMediator({map,calendar}) {
  return {selectClient(clientId) {
    map.highlightClient(clientId);
    calendar.filterByClient(clientId);
  }};
}
Try it: Subscribe two widgets to date changes, unsubscribe one, then write a mediator for a client selection.

Verify: Disposed widgets stop receiving updates and no widget imports another widget's internals.

08 / FIELD NOTE

Command, State and Chain of Responsibility

Command packages an action and its parameters; State delegates behaviour based on a valid lifecycle state; Chain of Responsibility passes a request through handlers until handled.

Why it matters

Actions need validation, audit and sometimes undo; complex lifecycles need explicit allowed transitions.

In practice

InvoiceIssueCommand validates, commits and audits; InvoiceState rejects paying a voided invoice; HTTP middleware chains authentication, validation and routing.

Pattern-by-pattern field guide

Commands describe requested work, States constrain lifecycle-dependent behaviour, and a Chain routes a request through responsibility-specific handlers.

Command

Represent an action as data plus an executor; useful for audit, queueing, replay and undo.

Example: Changing the delivery sequence becomes a reorder command with the actor, IDs and expected version.

Trade-off: Undo needs a compensating action, not blind reversal of an externally completed payment.

JavaScript example · Command
const command = {type:'ReorderStops', routeId:'r12',
  stopIds:['b','a','c'], expectedVersion:4};
const handlers={ReorderStops: async (cmd,service)=>
  service.reorder(cmd.routeId,cmd.stopIds,cmd.expectedVersion)};

State

Make allowed transitions explicit and reject invalid edges before persistence.

Example: A booking moves from draft to confirmed to completed or cancelled.

Trade-off: A display-only status string is not a state machine unless transition rules are enforced.

JavaScript example · State
const transitions={draft:['confirmed','cancelled'],
  confirmed:['completed','cancelled'],completed:[],cancelled:[]};
function changeStatus(current,next) {
  if (!transitions[current]?.includes(next)) throw Error('Invalid transition');
  return next;
}

Chain of Responsibility

Run handlers in a defined order and stop or delegate based on the result.

Example: Middleware enforces auth, tenant access, validation, then the business command.

Trade-off: Permission middleware must be applied to every protected route.

JavaScript example · Chain of Responsibility
const chain = (...steps)=>async request=>{
  for(const step of steps){
    const result=await step(request);
    if(result?.stop) return result.response;
  }
  return {status:200};
};
Try it: Create a command for a booking cancellation and a transition table covering allowed and denied paths.

Verify: Invalid edges and unauthorized requests never reach the write handler.

09 / FIELD NOTE

Iterator, Visitor and Memento

Iterator abstracts traversing a collection; Visitor separates operations from a fixed structure of types; Memento captures recoverable state without exposing internal implementation details.

Why it matters

These can support complex editors, AST tooling and history-aware workflows.

In practice

Iterate paginated event results; use a visitor on parsed code nodes for static analysis; store editor history snapshots for undo.

Pattern-by-pattern field guide

Iterator controls traversal, Visitor centralizes operations over a known type structure, and Memento stores a state snapshot for later restoration.

Iterator

Expose traversal without exposing internal storage or loading everything into memory.

Example: Read a paginated event API one page at a time, respecting end-of-list and errors.

Trade-off: Protect against repeated cursors that cause infinite loops.

JavaScript example · Iterator
async function* pages(fetchPage) {
  let cursor;const seen=new Set();
  do {const page=await fetchPage(cursor);yield* page.items;
    cursor=page.nextCursor;
    if(cursor&&seen.has(cursor)) throw Error('Repeated cursor');
    seen.add(cursor);
  } while(cursor);
}

Visitor

Dispatch an operation by element type when the element hierarchy stays relatively stable.

Example: A documentation AST renders headings, paragraphs and code blocks differently.

Trade-off: A union with a small switch is often clearer than a class visitor hierarchy.

JavaScript example · Visitor
const renderers={
  heading:n=>'<h2>'+escapeHtml(n.text)+'</h2>',
  paragraph:n=>'<p>'+escapeHtml(n.text)+'</p>'
};
const renderNode=node=>renderers[node.kind](node);

Memento

Capture a controlled snapshot to implement undo without exposing each editor's internals.

Example: Keep route reordering history so a dispatcher can restore the previous sequence.

Trade-off: Set limits; snapshots can retain sensitive data and grow without bound.

JavaScript example · Memento
function history(initial,limit=30) {
  let stack=[structuredClone(initial)];
  return {save:x=>{stack.push(structuredClone(x));stack=stack.slice(-limit);},
    undo:()=>structuredClone(stack.length>1?(stack.pop(),stack.at(-1)):stack[0])};
}
Try it: Iterate a fake paginated feed; then save and restore two different stop sequences.

Verify: All pages are visited once; undo restores a deep copy without mutating the saved snapshot.

10 / FIELD NOTE

Repository, Unit of Work and Dependency Injection

A repository provides an interface over persistence, Unit of Work coordinates related changes, and dependency injection supplies collaborators to the application instead of constructing them deep in a method.

Why it matters

Business logic stays testable and can evolve without rewriting every database or external-service call.

In practice

CheckoutService receives inventoryRepo and paymentGateway; its tests inject predictable fakes; integration tests still exercise the real database.

Pattern-by-pattern field guide

Repository is a domain-oriented persistence port; Unit of Work coordinates writes belonging to one transaction; DI supplies collaborators explicitly from the outside.

Repository

Define queries and writes using domain terms rather than leaking raw table structures into controllers.

Example: A client repository exposes findByIdForTenant and listActiveBookings rather than all SQL primitives.

Trade-off: Do not hide useful database operations behind a universal generic CRUD interface.

JavaScript example · Repository
function clientRepository(db) {
  return {findForTenant:(tenantId,id)=>db.get(
    'SELECT * FROM clients WHERE tenant_id=? AND id=?',[tenantId,id])};
}

Unit of Work

Commit related mutations together in one database transaction.

Example: A booking reservation and capacity decrement succeed or fail as one operation.

Trade-off: A database transaction cannot atomically include an external email or payment API.

JavaScript example · Unit of Work
async function reserve(db,booking) {
  return db.transaction(async tx=>{
    await tx.decrementCapacity(booking.slotId);
    return tx.insertBooking(booking);
  });
}

Dependency Injection

Pass dependencies at a composition root, making side effects substitutable in tests.

Example: A scheduler receives a clock and booking store so tests can freeze time.

Trade-off: A complex DI container is unnecessary when plain function parameters suffice.

JavaScript example · Dependency Injection
function createReminderService({clock,bookings,notify}) {
  return {async due(){const now=clock.now();
    for(const b of await bookings.dueBefore(now)) await notify.send(b);}};
}
Try it: Test a reminder service with an injected fake clock and a transaction that deliberately fails on the second write.

Verify: Tests never sleep, and failed writes leave no partial persisted reservation.

11 / FIELD NOTE

CQRS, Outbox and Saga

CQRS separates write commands from read models where their needs differ. Outbox stores an event transactionally with a business change so a worker can publish it reliably. Saga coordinates multi-step distributed workflows with compensating actions.

Why it matters

Read-heavy systems and integration-heavy systems require different consistency techniques.

In practice

An order and Outbox(OrderPlaced) record commit together, then a publisher sends the event; a search index updates eventually.

Pattern-by-pattern field guide

These are often combined but solve distinct system problems: separate query needs, reliable event handoff after commit, and coordination across multiple transactions.

CQRS

Keep command-side validation separate from query-side projections when their shapes and scaling requirements diverge.

Example: Calendar reads a flattened agenda projection while booking writes enforce availability in normalized tables.

Trade-off: Read models can lag writes; show a pending state or read your own write when required.

JavaScript example · CQRS
const commands={book:input=>bookingService.create(input)};
const queries={agenda:range=>agendaView.list(range)};
// A separate read schema is optional; separation starts with responsibilities.

Transactional Outbox

Store business changes and pending messages in one local transaction, then publish messages asynchronously.

Example: Confirm a booking and save BookingConfirmed to an outbox in the same commit.

Trade-off: Consumers must deduplicate because publication may occur more than once.

JavaScript example · Transactional Outbox
await db.transaction(async tx=>{
  await tx.insertBooking(booking);
  await tx.insertOutbox({id:eventId,type:'BookingConfirmed',bookingId:booking.id});
});
// Worker publishes pending rows, then marks them delivered.

Saga

Model a cross-service workflow as steps with explicit compensations for completed side effects.

Example: Reserve stock, request payment, schedule delivery; if scheduling fails, refund or release resources according to policy.

Trade-off: Compensation may fail too; track retries, durable state and human reconciliation.

JavaScript example · Saga
const steps=[
  {do:()=>reserveStock(),undo:()=>releaseStock()},
  {do:()=>chargePayment(),undo:()=>refundPayment()}
];
// Persist step outcomes; compensate successful steps in reverse order.
Try it: Write an outbox schema and a failure timeline for three saga steps.

Verify: A crash after commit does not lose the event, and duplicate dispatch is safe for consumers.

12 / FIELD NOTE

Anti-patterns and a pattern selection checklist

God objects, circular dependencies, shared global mutable state, premature generalisation and copy-pasted business rules create hidden coupling. Prefer named interfaces, explicit dependencies and tests of the reason a pattern exists.

Why it matters

Knowing when not to apply a pattern is as valuable as memorising its name.

In practice

Start with a simple mapping function; extract Strategy when algorithms become genuinely interchangeable and separately tested.

Pattern-by-pattern field guide

Do not optimize for the number of patterns in a diagram. Optimize for readable responsibilities, predictable changes, tested invariants and observable behaviour.

God object to cohesive services

Split an object when it owns unrelated workflows or requires unrelated collaborators.

Example: Move pricing policy, availability policy and delivery scheduling out of one 2,000-line CRM manager.

Trade-off: Avoid fragmentation into single-method classes that merely forward calls.

JavaScript example · God object to cohesive services
const bookingService={create:createBooking,cancel:cancelBooking};
const routingService={plan:planStops};
// Each boundary owns a distinct rule and its tests.

Dependency cycle to one-way contracts

Identify a stable lower-level contract or event boundary to remove cyclic module imports.

Example: Calendar can publish selection state through a shared model, rather than importing map internals and vice versa.

Trade-off: A message bus can make the graph harder to inspect if it replaces every direct call.

JavaScript example · Dependency cycle to one-way contracts
// UI adapters depend on shared selection state; not on one another.
const selection={current:null,select(id){this.current=id;}};
const mapView={selection},calendarView={selection};

Selection checklist

Check evidence: do implementations vary, does it remove duplication, can failures be isolated, and are tests simpler?

Example: Record the decision and its reversal criterion in a lightweight architecture note.

Trade-off: Avoid speculative extensibility with no change pressure.

JavaScript example · Selection checklist
const decision={problem:'provider payload mismatch',
  choice:'Adapter',alternatives:['inline mapping'],
  cost:'one boundary module',reviewWhen:'third provider added'};
Try it: Find one speculative interface and measure how many callers or alternate implementations actually use it.

Verify: The revised design reduces coupling or code without sacrificing needed behaviour.

RESEARCH EXPANSION · APPLIED ENGINEERING

13 / APPLIED RESEARCH

Ports and adapters (hexagonal architecture)

Define the core domain around business use cases, with ports that describe required services and adapters that implement HTTP, SQL, email or payment details. The direction of dependency points toward the domain.

Why it matters

Infrastructure changes should not rewrite rules such as inventory reservations.

In practice

Checkout use case receives InventoryPort and PaymentPort; tests pass fakes, while staging supplies real adapters.

Hands-on exercise · reveal the verification check
Try it

Extract one payment adapter from a checkout method.

Check your result

Domain tests run without network or database access.

Pattern-by-pattern field guide

Business use cases depend on ports—small contracts expressing what they need. Infrastructure adapters implement these contracts; HTTP handlers and CLIs are inbound adapters.

Outbound port and adapter

Define a domain-facing interface then implement SQL, in-memory or remote variants at the edge.

Example: A booking use case needs only saveBooking and findConflicts, not knowledge of SQL syntax.

Trade-off: A generic StorageService port can become an anemic wrapper around every database operation.

JavaScript example · Outbound port and adapter
const createBooking = repo => async input=>{
  const conflicts=await repo.findConflicts(input);
  if(conflicts.length) throw Error('Already booked');
  return repo.save(input);
};
const forTests=createBooking(fakeBookingRepository);

Inbound adapter

Translate transport payloads to a validated command and return a transport response.

Example: The same booking use case serves HTTP requests and an administrative CLI.

Trade-off: Never assume a validated UI means the server-side input is trusted.

JavaScript example · Inbound adapter
const httpHandler = useCase => async(req,res)=>{
  const input=validateBooking(req.body);
  const saved=await useCase(input);
  res.status(201).json({id:saved.id});
};
Try it: Run the exact same use case through a command-line adapter and an HTTP adapter.

Verify: Business unit tests run without a server or a database connection.

14 / APPLIED RESEARCH

Circuit breaker, retry, timeout and bulkhead

Retries recover transient errors, a timeout limits waiting, circuit breakers suspend calls to an unhealthy dependency, and bulkheads constrain resources per subsystem. Combine them carefully around idempotent operations.

Why it matters

A slow upstream service can consume every thread, connection or worker available to the app.

In practice

News importer gives the venue feed 2 retries with jitter, max concurrency 4 and a 5-second deadline.

Hands-on exercise · reveal the verification check
Try it

Inject 429, timeout and 503 responses into a test dependency.

Check your result

Import backs off safely while unrelated pages keep loading.

Pattern-by-pattern field guide

Resilience controls have distinct jobs. A timeout caps waiting; retry is for transient errors; a circuit breaker stops repeated calls to an unhealthy peer; a bulkhead isolates concurrency or resource pools.

Timeout

Set a deadline on each remote operation and handle cancellation explicitly.

Example: A map geocoder should fail or show an unresolved address rather than freeze the CRM.

Trade-off: Timeouts do not guarantee an upstream server rolled back the operation.

JavaScript example · Timeout
async function withDeadline(url,ms=4000) {
  const response=await fetch(url,{signal:AbortSignal.timeout(ms)});
  if(!response.ok) throw Error('HTTP '+response.status);
  return response.json();
}

Retry with backoff and jitter

Retry only errors likely to recover; bound attempts and the total deadline.

Example: An event importer retries a vendor's 503 but does not retry a malformed 400 indefinitely.

Trade-off: Never blindly retry non-idempotent payments or duplicate booking creation.

JavaScript example · Retry with backoff and jitter
async function retry(task,attempts=3) {
  for(let n=0;n<attempts;n++) {
    try{return await task();} catch(err) {
      if(n===attempts-1 || !err.transient) throw err;
      await new Promise(r=>setTimeout(r,Math.min(200*2**n,1500)+Math.random()*100));
    }
  }
}

Circuit Breaker

Track dependency failures, open the circuit after a threshold, then probe recovery after a cooldown.

Example: A broken public weather source stops consuming all request capacity.

Trade-off: Breaker state belongs to a specific dependency; avoid one breaker for unrelated services.

JavaScript example · Circuit Breaker
function circuit(task,{threshold=3,cooldown=10000}={}) {
  let failures=0,openedUntil=0;
  return async(...args)=>{
    if(Date.now()<openedUntil) throw Error('Dependency unavailable');
    try{const value=await task(...args);failures=0;return value;}
    catch(e){if(++failures>=threshold) openedUntil=Date.now()+cooldown;throw e;}
  };
}

Bulkhead

Reserve separate concurrency capacity for independent categories of work.

Example: Six slow venue scrapers should not starve invoice processing.

Trade-off: Limiting concurrency within one process does not enforce a cluster-wide global limit.

JavaScript example · Bulkhead
function semaphore(max) {
  let active=0;const waiting=[];
  return async fn=>{if(active>=max)await new Promise(r=>waiting.push(r));
    active++;try{return await fn();}finally{active--;waiting.shift()?.();}};
}
Try it: Inject 503s and timeouts with a test clock, then constrain importer concurrency independently of invoicing.

Verify: Retries are bounded, the breaker stops repeat work, and critical jobs remain responsive.

15 / APPLIED RESEARCH

Cache-aside and stale-while-revalidate

On a cache miss, retrieve from the canonical store and populate the cache with bounded freshness. For public content, serve stale data while a background refresh runs only when staleness is acceptable.

Why it matters

Caching can improve browsing speed but makes invalidation and consistency explicit design decisions.

In practice

Store artist biographies for 10 minutes; invalidate on edit; never cache another tenant's invoices under a shared key.

Hands-on exercise · reveal the verification check
Try it

Design cache keys for tenant and locale, then test invalidation.

Check your result

A changed biography appears within the promised freshness bound.

Pattern-by-pattern field guide

Caching introduces a second copy of data. State precisely what owns the truth, how fresh views must be, and how keys isolate tenants and locales.

Cache-aside

Check cache first, then fetch from the canonical store on miss; invalidate after writes.

Example: An artist biography is cached briefly, and an edit clears its matching key.

Trade-off: Avoid unbounded cache entries and mixing tenant data under shared IDs.

JavaScript example · Cache-aside
async function getArtist(id,cache,db) {
  const key='artist:'+id;
  let value=await cache.get(key);
  if(value) return value;
  value=await db.findArtist(id);
  if(value) await cache.set(key,value,{ttlSeconds:600});
  return value;
}

Stale-while-revalidate

Serve a known stale public view while refreshing it asynchronously when eventual freshness is acceptable.

Example: A town headlines page shows cached articles immediately and refreshes its index behind the scenes.

Trade-off: Never use stale cached permissions, bank balances or invoice ownership checks.

JavaScript example · Stale-while-revalidate
const policy={freshSeconds:60,staleSeconds:300};
async function news(cache,load) {
  const value=await cache.get('public-news');
  if(value?.age<policy.freshSeconds) return value.data;
  if(value?.age<policy.staleSeconds) {
    void refreshOnce('public-news',load);
    return value.data;
  }
  return load();
}
Try it: Design keys for tenant, locale and filter settings and model what happens on cache invalidation.

Verify: The source of truth wins after a write, stale data is visibly bounded, and tenant keys cannot collide.

16 / APPLIED RESEARCH

Specification, state and strategy patterns together

Use a Specification to describe reusable business predicates, State for allowed transitions and Strategy for interchangeable algorithms; avoid forcing all three into a one-function CRUD path.

Why it matters

Patterns earn their place when they make policy changes isolated, testable and explainable.

In practice

Eligibility spec checks an event's listing policy; its status machine rejects cancelled→paid, and ranking strategy chooses date or proximity.

Hands-on exercise · reveal the verification check
Try it

Draw a transition table for invoice states, and write forbidden-edge tests.

Check your result

No invalid status transition reaches persistence.

Pattern-by-pattern field guide

Combine patterns only when policies, lifecycle constraints and ranking choices each change independently. A single clear function remains valid for small workflows.

Specification

Express a named business predicate that can be combined with others.

Example: An event is publishable if its organizer is verified and its required location data is complete.

Trade-off: Avoid a dynamic query DSL when a predicate is used only once.

JavaScript example · Specification
const isVerified=e=>e.organizerVerified===true;
const hasAddress=e=>Boolean(e.address);
const and=(...rules)=>item=>rules.every(rule=>rule(item));
const isPublishable=and(isVerified,hasAddress);

State (combined)

Enforce a booking lifecycle before performing ranking or publication side effects.

Example: A cancelled booking must never appear as a deliverable route stop.

Trade-off: Do not scatter transition authorization across frontend buttons alone.

JavaScript example · State (combined)
const mayDispatch=booking=>
  booking.status==='confirmed' && booking.paid===true;

Strategy (combined)

Select a route ranking algorithm among eligible stops without modifying lifecycle rules.

Example: A dispatcher chooses proximity or deadline ranking for confirmed stops only.

Trade-off: A sorting heuristic is not a validated vehicle-routing optimizer.

JavaScript example · Strategy (combined)
const rank={deadline:(a,b)=>a.deadline-b.deadline,
  distance:(a,b)=>a.kmFromDepot-b.kmFromDepot};
const plan=(bookings,mode)=>bookings
  .filter(mayDispatch).sort(rank[mode]);
Try it: Implement an event eligibility rule, booking transition guard and two route sorters.

Verify: Ineligible and cancelled records never appear in either ranked route.

17 / APPLIED RESEARCH

Anti-corruption layer and Strangler migration

Wrap a legacy service in a translator that exposes clean domain concepts; move selected routes gradually behind a facade until old behaviour can be safely retired. Keep shared data ownership explicit during transition.

Why it matters

Big-bang rewrites are risky when existing records and integrations cannot disappear.

In practice

Expose modern /api/events through an adapter reading legacy event data; migrate one town before switching every consumer.

Hands-on exercise · reveal the verification check
Try it

Identify one legacy route and implement a compatibility adapter.

Check your result

Old and new consumers receive consistent values during migration.

Pattern-by-pattern field guide

Legacy modernization works best when old concepts are translated at one boundary and capabilities are replaced incrementally, with explicit data ownership and rollback.

Anti-corruption layer

Translate old models and vocabulary into a clean contract that the new domain understands.

Example: Convert a legacy dog-walk record into a generic CRM booking with one client ID and event time.

Trade-off: Do not let legacy status codes leak into all new consumers.

JavaScript example · Anti-corruption layer
function fromLegacyWalk(row) {
  return {clientId:String(row.dog_id),startsAt:row.walk_start,
    service:'walking',status:row.is_done?'completed':'scheduled'};
}

Strangler Fig

Route selected operations to a new implementation while leaving unreplaced paths on the old system.

Example: Move town-event reads one endpoint at a time to a database-backed provider.

Trade-off: Dual writes require reconciliation; do not switch a route without comparing outputs.

JavaScript example · Strangler Fig
const handlers={legacy:legacyEvents,new:databaseEvents};
async function listEvents(req) {
  const backend=req.flags.newEvents?'new':'legacy';
  return handlers[backend].list(req.town);
}
Try it: Shadow-read both implementations for one route without double-writing production records.

Verify: Results match on a known fixture, differences are logged without private data, and rollback takes one routing change.

18 / APPLIED RESEARCH

Dependency inversion versus abstraction for its own sake

Depend on a small behavioural contract only when alternative implementations or tests justify it. A direct SQL query may be clearer than ten pass-through classes; record when the interface will be reused.

Why it matters

Names like Service, Manager and Helper often hide coupling rather than reduce it.

In practice

Inject a clock to test scheduling deterministically; do not wrap Date.now in five layers without another purpose.

Hands-on exercise · reveal the verification check
Try it

Replace a global clock with one injected function in a scheduled job.

Check your result

Time-dependent tests run without sleeps or flaky real-time waits.

Pattern-by-pattern field guide

Dependency inversion keeps policy independent of unstable implementation details. It does not demand interfaces for every helper, class or SQL statement.

Dependency inversion

Inject external effects behind a small contract at the point where they vary or complicate tests.

Example: A scheduled reminder accepts a clock and sender so the policy can be tested in milliseconds.

Trade-off: Avoid a framework container for two functions with obvious collaborators.

JavaScript example · Dependency inversion
function reminders({now,send}) {
  return async items=>{
    for(const item of items) if(item.dueAt<=now()) await send(item);
  };
}
const testReminders=reminders({now:()=>1000,send:async()=>{}});

Abstraction budget

Use direct calls until a second implementation, meaningful test seam or volatile boundary justifies indirection.

Example: A single validated SQL query can be clearer than controller→manager→service→repository wrappers.

Trade-off: Do not confuse fewer files with better boundaries; protect complex business rules.

JavaScript example · Abstraction budget
// Simple, explicit boundary:
async function upcomingBookings(db,tenantId) {
  return db.all('SELECT * FROM bookings WHERE tenant_id=? AND starts_at > ?',[
    tenantId,new Date().toISOString()]);
}
Try it: Compare a five-layer forwarding chain with one service function and an injected clock.

Verify: Dependencies are discoverable, tests are deterministic, and the smallest coherent design wins.

Dependency boundaries

19 / FIELD NOTE

Ports and adapters: keep business rules separate from infrastructure

A use case depends on an abstraction for persistence, messaging or payments rather than directly on a specific database or vendor. Adapters implement those ports while tests can supply simple fakes. This is useful when external systems vary or the domain needs independent unit tests.

Why it matters

Changing how bookings are saved should not rewrite the rule about maximum daily capacity.

In practice

Define BookingRepository and ReminderSender ports; wire real implementations at application startup and use in-memory fakes in tests.

JavaScript
// Domain use case depends on a port, not a DB client
class ConfirmBooking {
  constructor(repo) { this.repo = repo; }
  async run(id) { return this.repo.confirm(id); }
}
Hands-on exercise · reveal the verification check
Try it

Extract one direct database call behind a narrow interface.

Check your result

The business rule is tested with no database connection.

20 / FIELD NOTE

Strategy and state patterns in pricing and booking lifecycles

Strategy replaces conditional selection of interchangeable algorithms, while State models behavior and permitted transitions based on a business object's lifecycle. A rule like a cancellation discount is a strategy; whether a booking may transition from paid to cancelled belongs to a state machine.

Why it matters

Clear distinctions prevent pattern-heavy code that hides policy in switch statements.

In practice

Select a pricing strategy for group size, then reject invalid booking transitions using an explicit transition table.

JavaScript · conceptual
const price = strategies[serviceType].calculate(booking);
if (!allowed[booking.status].includes(nextStatus)) throw Error('Invalid transition');
Hands-on exercise · reveal the verification check
Try it

Write five allowed and three forbidden transitions.

Check your result

Unit tests reject every forbidden transition.

21 / FIELD NOTE

Adapter, facade and anti-corruption layer: integrating legacy systems

An Adapter translates an incompatible interface, a Facade simplifies access to subsystems and an anti-corruption layer prevents external terminology from infecting the internal domain. Use them to integrate older systems without pretending legacy data semantics are identical to modern models.

Why it matters

Gradual migration is safer than forcing every consumer to understand legacy peculiarities.

In practice

Translate a legacy venue code into a typed Venue record through an adapter and expose it behind an application facade.

JavaScript
function fromLegacy(row) {
  return { id:String(row.venue_code), name:row.venue_name ?? 'Unknown' };
}
Hands-on exercise · reveal the verification check
Try it

Write an adapter with tests for missing and malformed legacy values.

Check your result

Domain code receives a stable contract without vendor-specific fields.

22 / FIELD NOTE

Observer versus Pub/Sub versus durable event messaging

An in-process Observer notifies subscribers inside one runtime, while Pub/Sub may distribute messages to external consumers. Durable messages add persistence, retries and delivery semantics that an ordinary callback does not have. Choose according to failure requirements, not naming similarity.

Why it matters

A missed UI repaint differs from a missed invoice email and deserves a different transport.

In practice

Use an in-memory observer for selected-artist changes, but a persisted outbox for booking confirmation notifications.

JavaScript · conceptual
// UI Observer handles ephemeral state; durable notifications use the outbox.
uiEvents.subscribe('selectedArtist', artist => render(artist));
Hands-on exercise · reveal the verification check
Try it

Simulate app crash after a booking commit but before notification.

Check your result

The durable event survives and is replayed safely.

23 / FIELD NOTE

Decorator, middleware and pipeline ordering

Decorator wraps behavior around an object without changing its interface, while middleware composes request stages such as tracing, authentication, validation and rate limiting. Ordering matters because authorization must occur before private data is returned and error handlers need to cover downstream stages.

Why it matters

Cross-cutting concerns can be reusable without contaminating domain logic.

In practice

Wrap an API client in timing and retry decorators, then show request IDs and authorization in server middleware.

JavaScript
const timed = fn => async (...args) => {
  const started = performance.now();
  try { return await fn(...args); }
  finally { console.info('duration_ms', performance.now()-started); }
};
Hands-on exercise · reveal the verification check
Try it

Reorder one middleware stage in a test environment.

Check your result

Tests demonstrate the security or error-handling difference.

24 / FIELD NOTE

Anti-patterns: god objects, singleton state and premature microservices

Patterns become harmful when used as decoration. Giant service classes couple unrelated domains, implicit singletons hide test state and excessive interfaces obscure data flow. Microservices create deployment and consistency obligations; choose them only when their isolation benefits justify those costs.

Why it matters

Maintainability depends on reducing the cost of change, not maximizing the pattern count.

In practice

Split a 3,000-line booking controller by use cases and domain responsibilities before proposing separate processes.

Refactoring note
// Avoid: one giant Service with UI, billing and SQL responsibilities.
// Prefer: BookingUseCase + InvoicePolicy + BookingRepository.
Hands-on exercise · reveal the verification check
Try it

Identify three smells in a hypothetical CRM module.

Check your result

Refactor one while preserving tested behavior.