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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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); }
}
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');
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.
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));
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.
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.