Applying Patterns in Real Systems: Selection, Combination & Anti-Patterns
"It's a statement that some capability we presume our software needs in the future should not be built now because “you aren't gonna need it”." — Martin Fowler, Yagni, martinfowler.com, 26 May 2015
Summary: Patterns are answers to forces, not decorations. This chapter teaches how to pick one (or none), which pairs travel together, how to read patterns in real code, how to spot over-engineering, how to refactor toward a pattern in small steps, and what happens to patterns when a feature leaves the monolith. Focus: Selection method, seven recurring combinations, pattern languages per domain, reading Go stdlib and Laravel internals, pattern density, Kerievsky's refactorings to patterns, anti-patterns in pattern use, service-scale patterns, ADRs, tests, and a full pricing-engine case study in Go and Laravel. Learning goal: Given a change request, name the force, list two or three candidate patterns with their consequences, choose the simplest that works, write the decision down, and test it; and given a codebase, tell which patterns it really uses and which names are decoration.
This page is the practice chapter of the design-patterns group. It assumes you have met the catalogue: the family overview is on Design Patterns: Origin and the Three Families, the individual patterns are on Creational, Structural and Behavioral patterns. Here we do not re-teach any pattern; we use them. Neighbours worth reading next to it: Code Smells and Refactoring (the smells that call for a pattern), the SOLID pages (OCP, DIP, SRP), Composition and the Law of Demeter, Design Quality Principles, Data Persistence in Design and Distribution of Components.
Page map
| If you are looking for | Go to |
|---|---|
| All the vocabulary in a few tables | Everything in one minute |
| Why "just apply patterns" fails | Why this chapter exists |
| Where the ideas come from, with sources | Where it comes from |
| Problem, forces, candidates, consequences, simplest | Pattern selection method |
| Factory + Strategy, Decorator + Chain, Command + Memento and the rest | Combinations that recur |
| Checkout, notifications, plugins, rules, reports | Pattern languages for a domain |
| Go stdlib and Laravel internals, with file paths | Reading open-source code |
| YAGNI, speculative generality, over-engineering signals | Pattern density |
| Replace conditional with strategy, form template method | Refactoring to patterns |
| Singleton abuse, factory explosion, anemic strategy, god mediator | Anti-patterns in pattern use |
| Gateway, ACL, sidecar, saga, outbox, CQRS | Patterns at service scale |
| Framework patterns vs your patterns | Framework vs application patterns |
| ADR, naming, tests | Documenting, Testing |
| What survives extraction to a microservice | Migrating a feature |
| A full design with tests and a decision log | Case study: pricing engine |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked later.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Force | A pressure that pushes the design in one direction | "Marketing adds a discount every month" | You pick a pattern for a force that does not exist |
| Consequence | What a pattern costs you after you adopt it | Strategy adds one class per variant | You only count the benefits |
| Candidate pattern | One of two or three plausible answers to the same forces | Strategy or a plain map | You fall in love with the first idea |
| Simplest that works | The option with the fewest moving parts that still absorbs the expected change | A switch for two variants | Interfaces appear before the second variant does |
| Pattern combination | Two patterns that each solve half of a problem | Factory + Strategy | Reinventing a pair the framework already ships |
| Pattern language | A set of patterns that fit one domain and refer to each other | Checkout: Pipeline, Strategy, Specification | Patterns picked one by one never fit together |
| Pattern density | How many pattern roles a module carries per unit of behaviour | 9 classes for 30 lines of logic | Nobody can find where the work happens |
| Speculative generality | Hooks and abstractions "just in case" | An interface with one implementation | Cost of carry, no payoff |
| Anti-pattern in pattern use | A pattern's name or shape without its benefit | OrderFactory that only calls new | Ceremony and false confidence |
| ADR | A one-page record of one decision and its consequences | "We use Strategy for discount rules" | Next person undoes it blindly |
| Framework pattern | A pattern the framework gives you and owns | Laravel Manager::extend() | You rebuild what exists |
| Application pattern | A pattern you add for your domain | Specification for discount eligibility | You reach for a framework hook that does not fit |
The selection method in seven questions.
| Step | Question | Output |
|---|---|---|
| 1 | What is the problem in one sentence, without a pattern name? | Problem statement |
| 2 | What are the forces: what changes, who changes it, how often? | Force list |
| 3 | Is plain code (function, switch, map, struct) enough for the forces we have today? | Stop, or continue |
| 4 | Which two or three patterns could answer these forces? | Candidates |
| 5 | What does each candidate cost: classes, indirection, test effort, team vocabulary? | Consequence table |
| 6 | Which is the simplest that works for the next change we can name? | Choice |
| 7 | Where do we write it down, and what would make us revisit it? | ADR, review trigger |
The seven combinations. Each pair is unpacked in Combinations that recur.
| Pair | The question the pair answers | Where you already use it |
|---|---|---|
| Factory + Strategy | Which algorithm, chosen by name or config | Laravel Manager::driver(), a Go map of funcs |
| Decorator + Chain of Responsibility | Stack behaviour around a call, with the option to stop | Go http.Handler middleware, Laravel Pipeline |
| Command + Memento | Undo, redo, audit | Editors, bulk-edit screens, saga compensation |
| Observer + Mediator | React to facts without knowing who reacts | Laravel Event::listen, a domain event bus |
| Composite + Visitor | One tree, many operations | File trees, ASTs, discount rule groups |
| Builder + Director | Step-by-step construction plus named recipes | Query builder plus a "monthly revenue" recipe |
| Proxy + Flyweight | Lazy, shared, immutable objects | Cached lookups, remote clients with a shared handle |
Where each family lives in your tools.
| Idea | Go | Laravel |
|---|---|---|
| Strategy | An interface or a func type, a map by name | A contract bound in the container, Manager drivers |
| Decorator and chain | func(http.Handler) http.Handler | Pipeline, HTTP middleware |
| Observer | A callback list, channels | Event::listen, model observers |
| Adapter | http.HandlerFunc | Flysystem adapters behind Storage |
| Factory | A constructor function, a map of constructors | Container::make, Manager::createXxxDriver |
| Specification | A func(Cart) bool combinator set | A small class set, or Eloquent query scopes for DB-side rules |
Why this chapter exists
A catalogue of 23 patterns teaches what each pattern is. It does not teach when to reach for one, which combinations are normal, or how to stop. The usual failure is not that nobody knows patterns; it is that people apply them as decoration, on day one, before a second variant exists. The Fowler quote above is the XP version of the same warning: build for the change you can name, not the one you can imagine.
| Pattern-first (the trap) | Problem-first (this chapter) |
|---|---|
| "Where can I use Strategy here?" | "What changes here, and who changes it?" |
| Interface on day one | Plain code on day one, a seam when the second variant arrives |
| One pattern per problem | A small language of two or three patterns |
| Names borrowed from the catalogue | Names borrowed from the domain |
| Design reviewed by pattern count | Design reviewed by change cost and test cost |
| Decision lives in someone's head | Decision lives in a one-page ADR |
The picture is the selection method as a loop. Notice that "is plain code enough?" comes before any candidate list, and that the last step feeds back to the forces: a pattern is a response to a situation, and when the situation changes, the choice is open again.
The analogy we reuse on this page: a kitchen drawer of gadgets. A cook owns an avocado slicer, a mandoline, a garlic press and a good knife. Most meals need the knife. The slicer is right on the one day you serve forty avocados. A kitchen where every dish is cut with a different gadget is slower, harder to clean, and impossible for a new cook to learn. Patterns are the gadgets; forces are the dishes.
Three common misunderstandings, up front
- "More patterns means a better design." Quality is measured by how cheaply the next change goes in and how cheaply the code is tested, not by the number of pattern names in the class list.
- "A pattern is a class diagram to copy." A pattern is a solution shape to a problem in a context, with consequences. The same pattern is a func type in Go, a tagged binding in Laravel and a class hierarchy in Java.
- "If I do not use a pattern I am designing badly." A
switchwith two cases is often the best design. A pattern becomes right when the forces show up.
Where it comes from
Pattern languages, 1970s. The idea that a set of patterns can form a language comes from the architect Christopher Alexander. We did not read Alexander's books for this page; the link to software is made in the page that introduced ADRs, which we did read: it says the consequences of one decision "become the context for subsequent ADRs", which it calls "similar to Alexander's idea of a pattern language: the large-scale responses create spaces for the smaller scale to fit into." (Michael Nygard, Documenting Architecture Decisions, 2011.) That is the sense used here: the pattern you choose first creates the room for the next one.
Gamma, Helm, Johnson, Vlissides, 1994. Design Patterns (the "Gang of Four" or GoF book) catalogued 23 patterns in three families. We did not read the book itself for this chapter; we used the refactoring.guru catalogue pages, which state the intents we cite. Example: "Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable." (refactoring.guru, Strategy.)
Evans and Fowler, Specifications. The paper by Eric Evans and Martin Fowler gives the idea we use in the case study: "The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against."
Kerievsky, 2004. Joshua Kerievsky's Refactoring to Patterns (we read the online catalogue of 27 refactorings on the Industrial Logic site, not the book) turned the question around: instead of designing with a pattern in advance, you get to the pattern from working code by small refactorings. The catalogue states each move as a problem and a solution. Example: "Problem: Conditional logic in a method controls which of several variants of a calculation are executed. Solution: Create a Strategy for each variant and make the method delegate the calculation to a Strategy instance." (Industrial Logic, Replace Conditional Logic with Strategy.)
Fowler, Yagni, 2015. The post separates presumptive features from real ones and names four costs of building them early: the cost of build, the cost of delay, the cost of carry ("this complexity makes it harder to modify and debug that software, thus increasing the cost of other features") and the cost of repair. It also cites Kohavi et al. for a base rate: "only ⅓ of them improved the metrics they were designed to improve."
Nygard, 2011. Documenting Architecture Decisions gives the ADR shape: title, context, decision, status, consequences; "The whole document should be one or two pages long." and "Agile methods are not opposed to documentation, only to valueless documentation."
Service-scale patterns. Eric Evans described the anti-corruption layer; Microsoft's Azure Architecture Center summarises it: "Implement a facade or adapter layer between different subsystems that don't share the same semantics." Chris Richardson's microservices.io defines the saga as "a reliably coordinated sequence of local transactions" and the outbox as storing the message "in the database as part of the transaction that updates the business entities". Fowler's CQRS page warns: "for most systems CQRS adds risky complexity." Fowler's Strangler Fig page (updated 22 August 2024) describes gradual replacement of a legacy system.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, and the fix.
Pattern selection method Must-know
In plain words: start from the problem and the forces, write down two or three ways to answer them, compare what each costs, and pick the one with the fewest moving parts that still absorbs the next change you can name.
Common misunderstanding: "Selection means finding the pattern that matches my problem." A catalogue lookup finds a pattern whose intent sounds like your problem. The decision depends on forces the catalogue cannot see: team size, release cadence, how many variants exist today, who owns them.
Definition: the method is a five-part chain: problem (one sentence, no pattern name) → forces (what changes, who changes it, how often, what must stay stable) → candidate patterns (two or three, including "plain code") → consequences (extra classes, indirection depth, test effort, vocabulary the team must share) → simplest that works (the candidate with the fewest parts that handles the next named change).
Step Who / what Output
1 W1 Product: "VIP gets 15%" Problem: discount depends on customer kind
2 W1 Dev: 1 variant, 1 team Force list: low variance today; money, so must be exact
3 W1 Dev: plain code enough? Yes: one function with a switch, a test table
4 W5 Product: "loyal: 1% per year" Forces change: 3 variants, still one team
5 W5 Dev: candidates switch, map of funcs, Strategy interface
6 W5 Dev: consequences map of funcs: 1 file, no new types; interface: 1 type per variant
7 W5 Choice map of funcs; ADR-0003 records why not interface yet
8 W12 Partner team adds kinds Forces change: second team => interface + registryReal scenarios: a discount function that grows from two to six cases (map of funcs, then Strategy); a notification service that gets a second channel (a switch is still fine) and a fifth (Manager with drivers); an export endpoint with CSV only (plain function) then PDF and XLSX (Template Method or Strategy, chosen by who adds formats).
| Situation | Typical candidates | Usually enough |
|---|---|---|
| One variant, no known second | Plain function | The function |
| Two variants, one team, stable | if, switch, map | A map of funcs |
| Three or more variants, one team | Map, Strategy | Strategy behind a factory function |
| Variants added by other teams or packages | Strategy + registry, plugin | Registry with extend() |
| Variants combine in trees | Composite | Composite + Specification |
| Behaviour must wrap other behaviour | Decorator, middleware | Chain of decorators |
| Reaction to facts, unknown reactors | Observer, event bus | Domain event + listeners |
Fix when you picked too early: inline the interface (Collapse Hierarchy, Inline Class), keep the tests, and wait for the next variant. See Pattern density.
Combinations that recur Must-know
In plain words: most real designs use patterns in pairs, because one pattern decides what varies and the other decides how the parts are wired.
Common misunderstanding: "A pair of patterns is twice as much design." A good pair is less design than either alone would need: the second pattern removes the boilerplate the first one would force on you.
Definition: a combination is two or more patterns whose roles interlock: one object plays a role in each. We cover seven that appear in nearly every codebase.
| Pair | Roles | Why they fit | Go snippet | Laravel snippet |
|---|---|---|---|---|
| Factory + Strategy | Factory chooses, Strategy computes | Callers name a variant, never a concrete type | combos/factorystrategy | Manager::driver() |
| Decorator + Chain of Responsibility | Each decorator wraps the next; any may stop | Stack cross-cutting behaviour in any order | combos/decoratorchain | Pipeline |
| Command + Memento | Command does and undoes; Memento restores | Undo without an inverse for every command | combos/commandmemento | CommandMemento.php |
| Observer + Mediator | Mediator owns subscriptions; observers react | Components never reference each other | combos/observermediator | Event::listen |
| Composite + Visitor | Composite is the tree; Visitor is an operation | New operations without editing nodes | combos/compositevisitor | CompositeVisitor.php |
| Builder + Director | Builder has steps; Director has recipes | Recipes are reusable and named | combos/builderdirector | Query builder + recipe |
| Proxy + Flyweight | Proxy loads lazily; Flyweight shares | One expensive immutable object per key | combos/proxyflyweight | Cache + shared object |
Request Layer What happens (Decorator + Chain)
1 GET /pay Recover defer recover(); calls next
2 RequireToken("s3cret") header missing -> 401, chain stops here
3 handler never reached
4 GET /pay Recover calls next
5 +token RequireToken header ok -> calls next
6 handler panics -> Recover turns it into 500Real scenarios: HTTP middleware (Decorator + Chain) in both stacks; a text or spreadsheet editor with undo (Command + Memento); Laravel domain events with several listeners (Observer + Mediator); an admin file tree that must show total size, permissions and a search (Composite + Visitor); report endpoints with named recipes (Builder + Director); a glyph or currency cache (Proxy + Flyweight).
Fix, Go (Factory + Strategy and Decorator + Chain):
// Package factorystrategy combines Factory and Strategy: the factory picks the strategy by name.
package factorystrategy
import "fmt"
// Shipper is the Strategy.
type Shipper interface{ Cost(weightGrams int) int64 }
type flat int64
func (f flat) Cost(int) int64 { return int64(f) }
type perKilo int64
func (p perKilo) Cost(w int) int64 { return int64(p) * int64((w+999)/1000) }
var registry = map[string]func() Shipper{
"standard": func() Shipper { return flat(500) },
"heavy": func() Shipper { return perKilo(300) },
}
// New is the Factory: the only place that knows concrete types.
func New(name string) (Shipper, error) {
mk, ok := registry[name]
if !ok {
return nil, fmt.Errorf("no shipper %q", name)
}
return mk(), nil
}// Package decoratorchain combines Decorator and Chain of Responsibility: each middleware wraps the next handler.
package decoratorchain
import (
"log"
"net/http"
)
// Middleware is a Decorator of http.Handler.
type Middleware func(http.Handler) http.Handler
// Chain builds the chain: the first middleware is the outermost one.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// Recover turns a panic into a 500 (one link of the chain).
func Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
log.Printf("panic: %v", v)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// RequireToken may stop the chain (the "responsibility" part): it does not call next.
func RequireToken(token string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}Fix, Laravel (Factory + Strategy as Manager, Decorator + Chain as Pipeline):
<?php
// Factory + Strategy in Laravel: Support\Manager is exactly this pair. getDefaultDriver() picks the strategy,
// createXxxDriver() is the factory method, extend() lets other packages add strategies.
namespace App\Shipping;
use Illuminate\Support\Manager;
interface Shipper
{
public function cost(int $weightGrams): int;
}
final class ShippingManager extends Manager
{
public function getDefaultDriver(): string
{
return $this->config->get('shipping.default', 'standard');
}
protected function createStandardDriver(): Shipper
{
return new class implements Shipper {
public function cost(int $weightGrams): int { return 500; }
};
}
protected function createHeavyDriver(): Shipper
{
return new class implements Shipper {
public function cost(int $weightGrams): int { return 300 * (int) ceil($weightGrams / 1000); }
};
}
}
// Usage: app(ShippingManager::class)->driver('heavy')->cost(2500); // 900
// Extension from another package: app(ShippingManager::class)->extend('drone', fn ($app) => new DroneShipper());<?php
// Decorator + Chain of Responsibility in Laravel: Pipeline wraps the destination in one closure per pipe.
namespace App\Checkout;
use Closure;
use Illuminate\Support\Facades\Pipeline;
final class ValidateStock
{
public function handle(CheckoutContext $ctx, Closure $next): mixed
{
if (! $ctx->stockOk) {
return $ctx->fail('out of stock'); // stops the chain: the "responsibility" part
}
return $next($ctx); // delegates to the next decorator
}
}
final class ApplyDiscounts
{
public function __construct(private \App\Pricing\PricingEngine $engine) {}
public function handle(CheckoutContext $ctx, Closure $next): mixed
{
$ctx->quote = $this->engine->price($ctx->cart);
return $next($ctx);
}
}
final class CheckoutContext
{
public ?\App\Pricing\Quote $quote = null;
public ?string $error = null;
public function __construct(public \App\Pricing\Cart $cart, public bool $stockOk = true) {}
public function fail(string $why): self
{
$this->error = $why;
return $this;
}
}
// Pipeline resolves class-string pipes from the container, so constructor injection works.
function checkout(CheckoutContext $ctx): CheckoutContext
{
return Pipeline::send($ctx)
->through([ValidateStock::class, ApplyDiscounts::class])
->thenReturn();
}The other five pairs have the same shape and live in the snippet folders (the lab runs them). Their Go code is combos/commandmemento, combos/observermediator, combos/compositevisitor, combos/builderdirector and combos/proxyflyweight; the Laravel versions are CommandMemento.php, ObserverMediator.php, CompositeVisitor.php, BuilderDirector.php and ProxyFlyweight.php.
Pattern languages for a domain Must-know
In plain words: in one domain the same handful of patterns keeps showing up and fitting together. Learn the handful for the domains you work in.
Common misunderstanding: "Pick the best pattern for each class separately." Patterns chosen one by one often fight each other; a language is chosen together so that each answer leaves room for the next.
Definition: a pattern language is a small set of patterns, with the order in which you apply them, for one kind of problem. Ours below are working habits, not published standards; the pairs inside them come from the catalogue.
| Domain | Pattern language (apply in this order) | Why this order |
|---|---|---|
| E-commerce checkout | Pipeline (Chain) → Strategy (pricing, shipping, payment) → Specification (eligibility) → Command (place order) → Observer (after-order events) → Outbox (publish reliably) | Steps first, then the varying algorithms inside steps, then reactions after commit |
| Notification system | Strategy (channel) → Factory or Manager (pick channel) → Template Method (message skeleton) → Decorator (rate limit, retry) → Observer (trigger) | Channels vary most; policies wrap them |
| Plugin system | Registry + Factory → Strategy (the plugin contract) → Adapter (third-party shapes) → Facade (host API) → Observer (hooks) | The host owns the contract; plugins plug into named points |
| Rules engine | Specification (conditions) → Strategy (actions) → Composite (rule groups) → Interpreter or data-driven Factory (load from storage) → Chain (ordering) | Conditions and actions are separate axes; trees come from combining |
| Report generation | Builder (steps) → Director (recipes) → Template Method (fixed skeleton) → Strategy (format) → Visitor (operations on the data tree) | Construction first, then formats and operations |
Step Checkout stage Pattern in use Force that chose it
1 1 Validate stock Chain of Responsibility Steps change order, some stop the flow
2 2 Price the cart Strategy + Composite Rules vary by campaign, combine in groups
3 3 Eligibility of a rule Specification Conditions combine: segment and window and total
4 4 Place the order Command Retry, audit, idempotency key
5 5 Tell the world Observer (after commit) Mail, stock, analytics must not block the order
6 6 Reliable publication Outbox Event must exist if and only if the order doesReal scenarios: the case study below is the pricing step of the checkout language; Laravel's own notification system is the notification language in 200 lines (ChannelManager extends Manager); Flysystem plus Laravel's Storage is the plugin language with adapters.
Fix when the language does not fit: if you need a pattern from outside the language, check whether the forces really differ; usually one of your earlier choices was too small.
Reading open-source code for patterns Must-know
In plain words: the fastest way to learn when a pattern is worth its cost is to read code where it already paid off. The standard library and the framework you use every day are full of them.
Common misunderstanding: "Framework code is too advanced to read." Most of these classes are 100 to 400 lines and have comments that explain the choice.
Definition: reading for patterns means opening a file, naming the role of each type (not the class name, which may lie), and asking which force the pattern serves.
Step Action What you learn
1 1 Open Support/Manager.php getDefaultDriver(), createDriver(), extend(): Factory + Strategy
2 2 Open Notifications/ChannelManager.php extends Manager: one 200-line file is the whole channel registry
3 3 Search for 'extends Manager' Cache, Mail, Auth, Filesystem, Notifications share the shape
4 4 Open Pipeline/Pipeline.php, then() array_reduce over pipes builds nested closures: Decorator chain
5 5 Open net/http/server.go, HandlerFunc A func type with one method: AdapterGo standard library (read from the Go repository on GitHub, src/ paths):
| File | Pattern you can see | Role of the types |
|---|---|---|
src/net/http/server.go | Strategy, Adapter, Decorator | Handler interface; HandlerFunc ("an adapter to allow the use of ordinary functions as HTTP handlers"); StripPrefix and TimeoutHandler wrap a Handler |
src/net/http/server.go | Registry, Mediator | ServeMux maps patterns to handlers and dispatches |
src/io/io.go | Decorator | TeeReader and LimitReader wrap a Reader and return a Reader |
src/sort/sort.go | Strategy | sort.Interface (Len, Less, Swap) is the strategy for sort.Sort |
src/database/sql/driver/driver.go | Abstract Factory, Bridge | Driver, Connector, Conn are the contract between database/sql and a driver |
Laravel framework (13.x branch, src/Illuminate/ paths):
| File | Pattern you can see | What to look for |
|---|---|---|
Container/Container.php | Factory, Registry, Decorator | bind, singleton, make, build; extend() wraps a resolved object; when() returns a ContextualBindingBuilder (Builder); tag()/tagged() group strategies |
Pipeline/Pipeline.php | Chain + Decorator | then() calls array_reduce over the reversed pipes with carry(); each pipe receives the passable and a $next closure |
Events/Dispatcher.php | Observer, Mediator | Event dispatcher: listen, dispatch, until (halt on first response), createClassListener turns Class@method into a closure |
Database/Query/Builder.php | Builder, Composite, Strategy | fluent where calls; forNestedWhere() and addNestedWhereQuery() nest groups (Composite); $grammar renders SQL per database (Strategy); toSql() |
Notifications/ChannelManager.php | Factory + Strategy | class ChannelManager extends Manager; channel($name) returns a driver; send and sendNow |
Support/Manager.php | Factory + Strategy + Registry | createDriver() tries customCreators, then a createXxxDriver method, else throws; extend() registers a creator |
Filesystem/FilesystemManager.php | Adapter, Factory | disk(), build(), createLocalDriver(), createS3Driver() wrap League Flysystem adapters behind one API |
Support/Facades/Pipeline.php | Facade | A static face (send, through, then, thenReturn) over the pipeline |
The Laravel docs say the same about storage: "Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge." That sentence is a pattern description: an adapter layer over a third-party library.
Fix: how to read a file for patterns: list the public methods, mark the one-method types, find where instances are created, and write the role names next to the class names.
Pattern density and over-engineering signals Important
In plain words: density is how much structure you carry per unit of behaviour. A little structure is cheap insurance; too much is a tax on every change.
Common misunderstanding: "Abstractions are free because they are only interfaces." Each interface adds a file, a name to remember, an indirection in every stack trace and a mock in every test. Fowler's cost of carry is exactly this: the code "adds some complexity to the software, this complexity makes it harder to modify and debug that software, thus increasing the cost of other features."
Definition: YAGNI ("You Aren't Gonna Need It") says not to build a capability you presume you will need. Speculative generality is the smell it targets; refactoring.guru describes it as code that "is created 'just in case' to support anticipated future features that never get implemented. As a result, code becomes hard to understand and support." The treatment it lists: Collapse Hierarchy, Inline Class, Inline Method, Remove Parameter. It also says when to ignore the smell: framework code whose users are not yet known.
Signal Check Likely cure
1 One implementation per interface grep "implements X" shows 1 Inline the interface
2 Class names end in Manager/Helper/Impl count them per package Rename by role or delete
3 Factory whose body is `new T(...)` read the body Call the constructor
4 Strategy with one strategy list the strategies Plain function
5 Parameters nobody passes grep call sites Remove Parameter
6 Mediator with a switch on event names count cases Split by area, or events
7 Pattern name in a class, none in domain ask "which force?" Rename or remove| Signal | Why it hurts | Counter-signal (keep it) |
|---|---|---|
| One implementation per interface | Extra file, mock, indirection | A test seam for a slow dependency (database, clock, HTTP) |
Manager, Helper, Util in names | Name says nothing about role | Framework base class named by the framework |
Factory around new | Hides a constructor | Factory that enforces an invariant or picks a type |
| Many layers per call | Stack traces become long | Layers that are real boundaries (module, process) |
| Config for everything | Behaviour moves out of code review | Values operators really change |
| "We may need it later" | Fowler: odds of being useful are low | A published API that cannot change later |
| Cost (Fowler) | Meaning in a pattern context |
|---|---|
| Cost of build | Writing the interface, the registry and the tests for variants that never come |
| Cost of delay | The real feature you did not ship while building the hook |
| Cost of carry | Every later change navigates the extra layer |
| Cost of repair | Wrong abstractions must be unpicked, usually under pressure |
Real scenarios: a repository interface with one Eloquent implementation and mocks everywhere (keep it only if tests really need the seam); a plugin system for an app with no third parties; a CQRS split for a CRUD admin.
Fix: measure (see Mechanics), delete the ceremony, keep the tests, and leave one comment that names the axis of variation so the next variant is cheap.
Refactoring to patterns Must-know
In plain words: instead of designing a pattern first, write plain code, wait for the pressure, and move toward the pattern in small safe steps that keep tests green.
Common misunderstanding: "Refactoring to patterns means rewriting." Each move is a sequence of mechanical steps; at every step the tests pass and the code ships.
Definition: Kerievsky's catalogue lists 27 refactorings (we read the list on the Industrial Logic site): Chain Constructors, Compose Method, Encapsulate Classes With Factory, Encapsulate Composite With Builder, Extract Adapter, Extract Composite, Extract Parameter, Form Template Method, Inline Singleton, Introduce Null Object, Introduce Polymorphic Creation With Factory Method, Limit Instantiation With Singleton, Move Accumulation To Collecting Parameter, Move Accumulation To Visitor, Move Creation Knowledge To Factory, Move Embellishment To Decorator, Replace Conditional Dispatcher With Command, Replace Conditional Logic With Strategy, Replace Constructors With Creation Methods, Replace Hard-Coded Notifications With Observer, Replace Implicit Language With Interpreter, Replace Implicit Tree With Composite, Replace One/Many Distinctions With Composite, Replace State-Altering Conditionals with State, Replace Type Code With Class, Unify Interfaces With Adapter, Unify Interfaces.
| Move (Kerievsky) | Problem as the catalogue states it | Smell it answers | Go or Laravel form |
|---|---|---|---|
| Replace Conditional Logic with Strategy | "Conditional logic in a method controls which of several variants of a calculation are executed." | Switch statements | map of funcs, container-tagged classes |
| Introduce Polymorphic Creation with Factory Method | "Classes in a hierarchy implement a method similarly except for an object creation step." | Duplicate code | constructor func passed in, createXxx method |
| Form Template Method | "Two methods in subclasses perform similar steps in the same order, yet the steps are different." | Duplicate code | Go: func fields or embedding; PHP: abstract base class |
| Unify Interfaces with Adapter | "Clients interact with two classes, one of which has a preferred interface." | Divergent interfaces | thin wrapper type, HandlerFunc style |
| Extract Composite | "Subclasses in a hierarchy implement the same Composite." | Duplicate code in subclasses | one Group type with children |
Step Refactoring step (Replace Conditional with Strategy) Tests
1 1 Extract each case body into a function (Extract Method) green
2 2 Give the functions one signature green
3 3 Put them in a map keyed by the old case label green
4 4 Replace the switch with a lookup + call green
5 5 Make unknown keys an error, not a silent default red then green (new test)
6 6 Only now: promote the func type to an interface if state greenReal scenarios: the discount switch from the one-minute table; an order-status switch (Replace State-Altering Conditionals with State); a pile of if (type == 'csv') in an exporter (Form Template Method).
Fix, Go (before and after):
// Package before is the starting point: one function, one growing switch.
package before
// Discount returns the discount in cents. Every new customer type edits this function.
func Discount(kind string, subtotal int64, years int) int64 {
switch kind {
case "regular":
return 0
case "vip":
return subtotal * 15 / 100
case "loyal":
pct := int64(years)
if pct > 10 {
pct = 10
}
return subtotal * pct / 100
case "staff":
return subtotal * 30 / 100
default:
return 0
}
}// Package after applies Replace Conditional Logic with Strategy, step by step.
package after
import "fmt"
// Customer carries the inputs the strategies need.
type Customer struct {
Kind string
Years int
}
// Discounter is the Strategy interface (the point of variation).
type Discounter interface {
Discount(c Customer, subtotal int64) int64
}
// DiscounterFunc adapts a function to Discounter.
type DiscounterFunc func(Customer, int64) int64
// Discount calls the function.
func (f DiscounterFunc) Discount(c Customer, s int64) int64 { return f(c, s) }
func percent(p int64) Discounter {
return DiscounterFunc(func(_ Customer, s int64) int64 { return s * p / 100 })
}
var strategies = map[string]Discounter{
"regular": percent(0),
"vip": percent(15),
"staff": percent(30),
"loyal": DiscounterFunc(func(c Customer, s int64) int64 {
return s * int64(min(c.Years, 10)) / 100
}),
}
// For is the creation point (Introduce Polymorphic Creation). An unknown kind is an error, not a silent zero.
func For(kind string) (Discounter, error) {
d, ok := strategies[kind]
if !ok {
return nil, fmt.Errorf("unknown customer kind %q", kind)
}
return d, nil
}Fix, Laravel (the same move with the container):
<?php
// app/Services/CustomerDiscount.php — starting point: one growing match.
namespace App\Services;
final class CustomerDiscount
{
public function for(string $kind, int $subtotal, int $years): int
{
return match ($kind) {
'regular' => 0,
'vip' => intdiv($subtotal * 15, 100),
'loyal' => intdiv($subtotal * min($years, 10), 100),
'staff' => intdiv($subtotal * 30, 100),
default => 0, // a typo in $kind silently gives no discount
};
}
}<?php
// Replace Conditional Logic with Strategy: one class per variant, one place that creates them.
namespace App\Discounts;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
interface Discounter
{
public function kind(): string;
public function discount(int $subtotal, int $years): int;
}
final class Vip implements Discounter
{
public function kind(): string { return 'vip'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * 15, 100); }
}
final class Loyal implements Discounter
{
public function kind(): string { return 'loyal'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * min($years, 10), 100); }
}
// Creation point: the container injects every class tagged 'discounters' (see the service provider below).
final class DiscounterFactory
{
/** @var array<string, Discounter> */
private array $byKind = [];
/** @param iterable<Discounter> $discounters */
public function __construct(#[Tag('discounters')] iterable $discounters)
{
foreach ($discounters as $d) {
$this->byKind[$d->kind()] = $d;
}
}
public function for(string $kind): Discounter
{
return $this->byKind[$kind] ?? throw new InvalidArgumentException("unknown customer kind [$kind]");
}
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->tag([Vip::class, Loyal::class], 'discounters');
// A new customer kind is a new class plus one name in that list; DiscounterFactory never changes.Anti-patterns in pattern use Important
In plain words: these are mistakes made while using patterns: the name is there, the benefit is not.
Common misunderstanding: "If it follows the GoF diagram it is fine." A diagram-shaped class with no force behind it is overhead.
Definition: an anti-pattern in pattern use is a structure that borrows a pattern's shape or name and removes its payoff, usually by adding hidden coupling or ceremony. The wider smell catalogue is on Code Smells and Refactoring.
| Anti-pattern | Symptom | Why it happens | Cure |
|---|---|---|---|
| Singleton abuse | Settings::instance() or a global DB read from everywhere | Convenience; "there is only one" | Pass the dependency; let the container own lifetime (DIP) |
| Factory explosion | AbstractFooFactoryFactory, one factory per class | Factory by reflex | Call the constructor; keep one factory per real choice |
| Interface-for-everything | IUserService with one UserService | "Program to an interface" misread | Interface where a second implementation or a test seam exists |
| Anemic strategy | A Strategy with one body and no state | Premature OCP | Plain function; extract when variant 2 arrives |
| God mediator | One class with every screen or event rule | Mediator absorbs logic | One mediator per area; events with local listeners |
| Pattern-named class with no pattern | OrderFactory that only calls new Order | Naming by decoration | Rename by role or remove |
| Observer chain with hidden order | Listener A fires an event that triggers B | Events used as control flow | Explicit orchestration for ordered work |
| Decorator stack nobody can list | Behaviour order depends on registration order | Middleware sprawl | One documented chain, test the order |
| Visitor on an unstable tree | Every new node type edits every visitor | Visitor chosen for the wrong axis | Methods on nodes, or a closed sum type |
Step Event Smell it creates
1 1 Dev adds Settings::instance() for convenience Hidden global
2 2 Test needs different settings Static reset in setUp()
3 3 Second test file forgets the reset Order-dependent failures
4 4 Parallel test runner Flaky suite
5 5 Fix: inject Settings, drop the static Tests pass in any orderReal scenarios: a Laravel app where every class calls Settings::instance(); a Go service with a package-level var DB *sql.DB; a UI form whose mediator grows to 60 cases.
Fix, Go and Laravel:
// Package before collects four anti-patterns that wear a pattern's name.
package before
import "database/sql"
// 1. Singleton abuse: a hidden global every caller reaches for.
var DB *sql.DB
// OrderCount cannot be tested without a real database.
func OrderCount() (n int, err error) {
err = DB.QueryRow("SELECT count(*) FROM orders").Scan(&n)
return n, err
}
// 2. Pattern-named class with no pattern: a "factory" that is just a constructor with an extra word.
type Order struct{ ID string }
type OrderFactory struct{}
func (OrderFactory) CreateOrder(id string) *Order { return &Order{ID: id} }
// 3. Anemic strategy: an interface with one implementation, no second variant in sight.
type TaxStrategy interface{ Tax(net int64) int64 }
type FlatTaxStrategy struct{}
func (FlatTaxStrategy) Tax(net int64) int64 { return net * 20 / 100 }
// 4. God mediator: every rule of every screen lives in one switch.
type Mediator struct{ state map[string]string }
func (m *Mediator) Notify(sender, event string) {
switch sender + ":" + event {
case "country:changed":
m.state["state"] = ""
case "cart:changed":
m.state["total"] = "recomputed"
case "coupon:applied":
m.state["total"] = "recomputed"
m.state["banner"] = "shown"
}
}// Package after shows the plain versions that replace the four anti-patterns.
package after
import (
"context"
"database/sql"
)
// 1. Pass the dependency. The caller owns the lifetime; tests pass a fake.
type OrderCounter struct{ DB *sql.DB }
// Count runs the query on the injected handle.
func (o OrderCounter) Count(ctx context.Context) (n int, err error) {
err = o.DB.QueryRowContext(ctx, "SELECT count(*) FROM orders").Scan(&n)
return n, err
}
// 2. A struct literal is enough. Add a constructor only when it enforces an invariant.
type Order struct{ ID string }
// 3. One variant: a plain function. Introduce an interface when the second variant arrives.
func Tax(net int64) int64 { return net * 20 / 100 }
// 4. Small mediators, one per screen area, each with a narrow job.
type CartPanel struct{ Recompute func() }
// OnCouponApplied is a local reaction, not a branch in a global switch.
func (p CartPanel) OnCouponApplied() { p.Recompute() }<?php
// Four anti-patterns that wear a pattern's name.
namespace App\Smells;
use Illuminate\Support\Facades\DB;
// 1. Singleton abuse: a static accessor hides the dependency.
final class Settings
{
private static ?self $instance = null;
public array $values = [];
public static function instance(): self { return self::$instance ??= new self(); }
}
// 2. Pattern-named class with no pattern: a "factory" that only calls new.
final class OrderFactory
{
public function createOrder(array $data): Order { return new Order($data); }
}
// 3. Anemic strategy: an interface with one implementation and no second variant in sight.
interface TaxStrategy { public function tax(int $net): int; }
final class FlatTaxStrategy implements TaxStrategy
{
public function tax(int $net): int { return intdiv($net * 20, 100); }
}
// 4. God mediator: every rule of every screen in one switch.
final class FormMediator
{
public function notify(string $sender, string $event, array &$state): void
{
switch ("$sender:$event") {
case 'country:changed': $state['state'] = null; break;
case 'cart:changed': $state['total'] = 'recomputed'; break;
case 'coupon:applied': $state['total'] = 'recomputed'; $state['banner'] = 'shown'; break;
}
}
}<?php
// The plain versions that replace the four anti-patterns.
namespace App\Smells;
use Illuminate\Support\Facades\Config;
// 1. Use the framework's own singleton: config() / the container. Inject what the class really needs.
final readonly class TaxCalculator
{
public function __construct(private int $ratePercent) {}
// 3. One variant: a plain method. Extract an interface when the second variant arrives.
public function tax(int $net): int { return intdiv($net * $this->ratePercent, 100); }
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->bind(TaxCalculator::class, fn () => new TaxCalculator(Config::integer('tax.rate_percent')));
// 2. A constructor is enough. Order's own constructor enforces its invariants.
// 4. Livewire/Alpine events or one small component per screen area replace the god mediator;
// the server side uses one listener per reaction (see the Event section of the page).Patterns at service scale Must-know
In plain words: the famous service-level patterns are GoF ideas with a network in the middle. If you know Facade, Adapter, Proxy, Observer, Command and Mediator, you already know the shape of gateway, ACL, sidecar, outbox and saga; what changes is the failure model.
Common misunderstanding: "Service patterns are a different subject from design patterns." They are the same ideas, but every call can now time out, be duplicated or arrive late, so each pattern needs a timeout, an idempotency key or a compensation.
Definition: the mapping below is our own reading (inference, not from the sources). The definitions quoted are from the sources named in each row.
| Service-scale pattern | Closest GoF idea | What the network adds | Where to read more |
|---|---|---|---|
| API gateway | Facade + Proxy. Microsoft: "Route requests to multiple services or multiple service instances using a single endpoint." | Auth, rate limits, routing, failure | API Gateway, BFF and Service Mesh |
| Anti-corruption layer (ACL) | Adapter + Facade. "Implement a facade or adapter layer between different subsystems that don't share the same semantics." | Separate wire DTOs, versioning | Service boundaries |
| Sidecar | Decorator or Proxy as a separate process. "Deploy application components into a process or container separate from the main application to provide isolation and encapsulation." | Shared lifecycle, extra hop | Microkernel and plugin |
| Transactional outbox | Observer made durable. Store the message "in the database as part of the transaction that updates the business entities." | At-least-once delivery, dedup | Outbox pattern |
| Saga | Command + State + Mediator. "a reliably coordinated sequence of local transactions" | Compensation, partial failure | Saga pattern |
| CQRS | Command and Query separated. "for most systems CQRS adds risky complexity" (Fowler) | Read model lag | Event Sourcing and CQRS |
| Circuit breaker | Proxy + State | Open, half-open, closed | Circuit breaker |
| Idempotent consumer | Command + dedup store | At-least-once delivery | Idempotent consumers and inbox |
| Strangler fig | Facade/Proxy that routes between old and new | Two systems at once | Monolith vs microservices vs modular |
Step Call (pricing as a service, gateway in front) Pattern at work
1 1 Client -> Gateway: POST /checkout Facade: one entry point
2 2 Gateway -> Checkout: auth passed, route Proxy: routing, rate limit
3 3 Checkout -> Pricing (Remote adapter): quote Proxy adapter: timeout 300 ms
4 4 Pricing: Engine.Price(cart) Strategy + Composite (inside)
5 5 Pricing unreachable Fallback: no-discount quote, logged
6 6 Checkout commits order + outbox row Outbox: one local transaction
7 7 Relay publishes OrderPlaced Observer across servicesReal scenarios: an e-commerce gateway; a billing service that translates a legacy ERP's field names behind an ACL; a service mesh sidecar for mTLS; an order flow that spans payment and stock with a saga.
Fix: keep the local patterns inside the service, make the boundary explicit (port, adapter, wire DTO), and treat each remote call as a Proxy that must have a timeout and a degraded answer.
Framework patterns vs application patterns Important
In plain words: some patterns are provided and maintained by the framework; others you build for your domain. Use the first kind through their extension points, and write the second kind yourself.
Common misunderstanding: "I should re-implement Strategy cleanly instead of using Manager." If the framework already ships the shape, copying it gives you code to maintain and a second vocabulary to teach.
Definition: a framework pattern is a pattern whose skeleton is in the framework and whose variation points are documented hooks (Manager::extend, Storage::extend, Notification::extend, middleware, Event::listen, a Go http.Handler). An application pattern is a pattern whose forces belong to your domain (pricing rules, eligibility, report recipes).
| Question | Framework pattern | Application pattern |
|---|---|---|
| Who owns the skeleton? | The framework | Your team |
| How do you vary it? | Documented extension point | New class or function |
| Upgrade risk | Follows the framework's release notes | Yours |
| Example (Laravel) | Notification::extend('voice', ...) | Spec::and(Spec::segment('vip'), ...) |
| Example (Go) | http.Handler and HandlerFunc | Rule and Group in the pricing package |
Real scenarios: registering a custom disk with Storage::extend, a custom notification channel with Notification::extend, middleware around a Go mux; versus a domain Specification no framework would ever ship.
Fix, Laravel (extension points):
<?php
// Three framework extension points, all the same shape: a named strategy registered at runtime.
namespace App\Providers;
use App\Notifications\VoiceChannel;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;
final class ExtendPointsServiceProvider extends ServiceProvider
{
public function boot(): void
{
// 1. Notifications: ChannelManager extends Support\Manager, so extend() adds a channel (strategy by name).
Notification::extend('voice', fn (Application $app) => new VoiceChannel());
// 2. Filesystem: FilesystemManager builds a Flysystem adapter per disk; a custom driver returns a FilesystemAdapter.
Storage::extend('audited-local', function (Application $app, array $config) {
$adapter = new LocalFilesystemAdapter($config['root']);
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
});
}
}<?php
// Reading Illuminate\Pipeline\Pipeline (src/Illuminate/Pipeline/Pipeline.php): then() reduces the pipes
// with array_reduce into nested closures, so each pipe is a Decorator of the next one.
// Re-implemented here in ten lines to show that the pattern is small.
namespace App\Internals;
use Closure;
final class MiniPipeline
{
/** @param list<callable(mixed, Closure): mixed> $pipes */
public static function run(mixed $passable, array $pipes, Closure $destination): mixed
{
$stack = array_reduce(
array_reverse($pipes),
fn (Closure $next, callable $pipe) => fn ($p) => $pipe($p, $next),
$destination,
);
return $stack($passable);
}
}
// MiniPipeline::run($order, [$validate, $price, $reserve], fn ($o) => $o);Documenting pattern use: ADR and naming Important
In plain words: write one short record of why you chose the pattern, and name classes after the domain role so the code explains itself.
Common misunderstanding: "Pattern names in class names document the design." DiscountStrategyFactoryImpl says how it was built, not what it is for. DiscountRules says what it is for.
Definition: an Architecture Decision Record (ADR) is a short document with a title, context, decision, status and consequences (Nygard). Naming rules: role over pattern (Pricer, not PricingStrategyManager); a pattern word only when the role is the pattern (Registry, Specification); the same word for the same concept in code, tests, tickets and docs.
ADR-0007: Pricing rules are Strategy + Composite, built by a registry Factory
1 Status: Accepted (2026-11-25)
2 Context: Marketing adds rule kinds monthly; rules combine (stack, best-of, first).
3 A switch in checkout was edited by two teams and broke VIP prices twice.
4 Decision: Rule interface (Strategy); Group (Composite); Factory.Register(kind, ctor);
5 eligibility as Specification; money as int64 minor units.
6 Consequences (all):
7 + new kind = one type + one Register call; no edit to Engine or Factory
8 + rules are pure: tested without database or clock
9 - 4 concepts to learn; rule trees need a viewer for support staff
10 - registry is global to the Factory instance; kinds must be unique
11 Revisit when: rules need cross-cart state (loyalty points) or run in another service.| Naming habit | Good | Smell |
|---|---|---|
| Role names | Pricer, Quote, Rule | PricingStrategyManagerImpl |
| Pattern word only for the pattern | Registry, Specification | OrderHelper, CartUtil |
| Same word everywhere | "rule" in code, tickets, admin UI | "rule", "promotion", "offer" for one thing |
| Verb for commands | PlaceOrder | OrderProcessor |
Real scenarios: docs/adr/0007-pricing-rules.md in the repo; a pull request template with a "pattern choice" line; a one-line comment at the point of variation.
Fix: keep ADRs short (one or two pages, per Nygard), number them, never edit the decision of an accepted ADR (supersede it), and link the ADR from the code at the seam.
Testing strategies for patterned code Important
In plain words: patterns exist partly to make code testable. Test each role on its own, test the wiring once, and test the contract at every boundary that can be swapped.
Common misunderstanding: "I need to mock every interface." Prefer real small objects (a pure Strategy, a Specification) over mocks; mock only slow or non-deterministic things.
Definition: seven test layers for patterned code.
| Layer | What it tests | Style | Example in this chapter |
|---|---|---|---|
| Role unit tests | One Strategy or Specification | Table tests, no mocks | TestSpecifications, TestBuyXGetY |
| Composite tests | Group modes and nesting | Table tests with real children | TestGroupModes |
| Factory tests | Valid and invalid definitions | Error cases are first-class | TestFactoryRejectsBadDefinitions |
| Wiring test | The assembled tree gives the expected quote | One golden JSON | TestFactoryBuildsTreeAndEngineQuotes |
| Contract test | Two adapters agree | Same cart, both adapters | TestParity in migrate |
| Chain order test | The order and short-circuit of a chain | Fake handlers | TestChainOrderAndShortCircuit |
| Architecture test | Dependencies point the allowed way | Static check in CI | internal/ packages, import rules |
Step Test run Result
1 1 go test ./pricing rules pure, tree built from JSON
2 2 add time.Now() inside a rule TestRulesArePure may pass, but the quote changes per run
3 3 move the clock into Cart.Now deterministic again
4 4 go test ./migrate TestParity: local and remote quotes equal
5 5 stop the pricing server TestFallbackWhenServiceIsDown: no-discount quoteReal scenarios: a flaky discount test caused by now() inside a rule; a remote client that silently drifted from the in-process one until a contract test was added.
Fix, Laravel: use Event::fake() for listeners, Http::fake() for the remote adapter, and plain PHPUnit for rules (see the test in the case study).
Migrating a feature to a microservice: which patterns survive Must-know
In plain words: patterns inside the feature move with it; patterns between the feature and the rest turn into network contracts.
Common misunderstanding: "Extraction just means copying the folder." The in-process calls become remote calls, and each one needs a timeout, a fallback, a schema and a contract test.
Definition: extraction in small steps, in the order Fowler's strangler-fig idea suggests: put a port in front, make a second adapter, route a slice of traffic, then retire the old one.
Step Action Pattern
1 1 Define Pricer port; checkout depends only on it Facade / DIP
2 2 Local adapter calls Engine in-process Adapter
3 3 Wire DTOs for request and quote ACL
4 4 Service exposes POST /quote using the same Engine Facade
5 5 Remote adapter with timeout and fallback Proxy
6 6 Contract test: Local and Remote agree Contract test
7 7 Route 5% of checkouts to Remote Strangler / feature flag
8 8 Remove Local from checkout, keep it as fallback Degraded mode| Pattern | Survives how | Notes |
|---|---|---|
| Strategy, Composite, Specification, Factory | Unchanged, inside the service | They never crossed the boundary |
| Facade | Becomes the public API | Version it |
| Adapter | Becomes the ACL | Translate, do not leak domain types |
| Proxy | Appears as the remote client | Timeout, retry, fallback |
| Observer | Becomes domain events plus outbox | At-least-once, idempotent consumers |
| Command | Becomes a message with an idempotency key | Retried safely |
| Mediator | Becomes saga orchestration | Compensation instead of rollback |
| Singleton | Dies | Process-wide state does not exist across replicas |
| Memento | Becomes persisted state | Snapshots go to a database |
Fix, Go and Laravel:
// Package migrate shows a pricing feature leaving the monolith: one port, two adapters, one wire contract.
package migrate
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"academy/patterns-in-practice/pricing"
)
// Pricer is the port the checkout code depends on. It is the same in the monolith and after extraction.
type Pricer interface {
Quote(ctx context.Context, c pricing.Cart) (pricing.Quote, error)
}
// Local is the in-process adapter used inside the monolith.
type Local struct{ Engine pricing.Engine }
// Quote prices in the same process.
func (l Local) Quote(_ context.Context, c pricing.Cart) (pricing.Quote, error) {
return l.Engine.Price(c), nil
}
// --- wire contract (the Anti-Corruption Layer keeps domain types off the network) ---
type wireLine struct {
SKU string `json:"sku"`
Category string `json:"category"`
Qty int `json:"qty"`
Unit int64 `json:"unit_minor"`
}
type wireRequest struct {
Lines []wireLine `json:"lines"`
Segment string `json:"segment"`
Coupon string `json:"coupon,omitempty"`
NowUnix int64 `json:"now_unix"`
}
type wireQuote struct {
Subtotal int64 `json:"subtotal_minor"`
Discount int64 `json:"discount_minor"`
Total int64 `json:"total_minor"`
}
func toWire(c pricing.Cart) wireRequest {
w := wireRequest{Segment: c.Segment, Coupon: c.Coupon, NowUnix: c.Now.Unix()}
for _, l := range c.Lines {
w.Lines = append(w.Lines, wireLine{l.SKU, l.Category, l.Qty, int64(l.Unit)})
}
return w
}
func fromWire(w wireRequest) pricing.Cart {
c := pricing.Cart{Segment: w.Segment, Coupon: w.Coupon, Now: time.Unix(w.NowUnix, 0).UTC()}
for _, l := range w.Lines {
c.Lines = append(c.Lines, pricing.Line{SKU: l.SKU, Category: l.Category, Qty: l.Qty, Unit: pricing.Money(l.Unit)})
}
return c
}
// Handler is the service side: it exposes the engine over HTTP.
func Handler(e pricing.Engine) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req wireRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
q := e.Price(fromWire(req))
_ = json.NewEncoder(w).Encode(wireQuote{int64(q.Subtotal), int64(q.Discount), int64(q.Total)})
})
}
// Remote is the Proxy adapter: same port, but the call crosses the network, so it needs a timeout and a fallback.
type Remote struct {
BaseURL string
Client *http.Client
Fallback Pricer // optional degraded behaviour, e.g. "no discount"
}
// Quote calls the pricing service; on failure it uses the fallback if one is set.
func (r Remote) Quote(ctx context.Context, c pricing.Cart) (pricing.Quote, error) {
q, err := r.call(ctx, c)
if err != nil && r.Fallback != nil {
return r.Fallback.Quote(ctx, c)
}
return q, err
}
func (r Remote) call(ctx context.Context, c pricing.Cart) (pricing.Quote, error) {
body, err := json.Marshal(toWire(c))
if err != nil {
return pricing.Quote{}, err
}
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/quote", bytes.NewReader(body))
if err != nil {
return pricing.Quote{}, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := r.Client.Do(req)
if err != nil {
return pricing.Quote{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return pricing.Quote{}, fmt.Errorf("pricing service: status %d", resp.StatusCode)
}
var w wireQuote
if err := json.NewDecoder(resp.Body).Decode(&w); err != nil {
return pricing.Quote{}, err
}
return pricing.Quote{Subtotal: pricing.Money(w.Subtotal), Discount: pricing.Money(w.Discount), Total: pricing.Money(w.Total)}, nil
}package migrate
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/patterns-in-practice/pricing"
)
func engine() pricing.Engine {
return pricing.Engine{Root: pricing.Group{ID: "root", Mode: pricing.Stack, Children: []pricing.Rule{
pricing.PercentOff{ID: "vip", When: pricing.InSegment("vip"), Percent: 15},
pricing.FixedOff{ID: "welcome", When: pricing.MinSubtotal(5000), Amount: 700},
}}}
}
var sample = pricing.Cart{
Segment: "vip",
Now: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC),
Lines: []pricing.Line{{SKU: "novel", Category: "books", Qty: 2, Unit: 4000}},
}
// TestParity is the contract test: the in-process and the remote adapter must agree.
func TestParity(t *testing.T) {
srv := httptest.NewServer(Handler(engine()))
defer srv.Close()
local := Local{Engine: engine()}
remote := Remote{BaseURL: srv.URL, Client: srv.Client()}
a, _ := local.Quote(context.Background(), sample)
b, err := remote.Quote(context.Background(), sample)
if err != nil {
t.Fatal(err)
}
if a.Subtotal != b.Subtotal || a.Discount != b.Discount || a.Total != b.Total {
t.Fatalf("adapters disagree: local %+v remote %+v", a, b)
}
}
func TestFallbackWhenServiceIsDown(t *testing.T) {
down := httptest.NewServer(http.NotFoundHandler())
url := down.URL
down.Close()
noDiscount := Local{Engine: pricing.Engine{}}
r := Remote{BaseURL: url, Client: &http.Client{}, Fallback: noDiscount}
q, err := r.Quote(context.Background(), sample)
if err != nil || q.Total != q.Subtotal {
t.Fatalf("want undiscounted fallback, got %+v err=%v", q, err)
}
}<?php
// The same port in the monolith and after extraction. Checkout code depends on Pricer only.
namespace App\Pricing;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
interface Pricer
{
public function quote(Cart $cart): Quote;
}
// In-process adapter: used inside the monolith.
final readonly class LocalPricer implements Pricer
{
public function __construct(private PricingEngine $engine) {}
public function quote(Cart $cart): Quote { return $this->engine->price($cart); }
}
// Proxy adapter: same port, but the call crosses the network, so it needs a timeout, a retry and a fallback.
final readonly class RemotePricer implements Pricer
{
public function __construct(private string $baseUrl, private Pricer $fallback) {}
public function quote(Cart $cart): Quote
{
try {
$r = Http::baseUrl($this->baseUrl)
->timeout(1)->retry(2, 100, throw: false)
->post('/quote', $this->toWire($cart)) // wire DTO = the Anti-Corruption Layer
->throw()->json();
} catch (ConnectionException|\Illuminate\Http\Client\RequestException $e) {
Log::warning('pricing service unavailable, using fallback', ['error' => $e->getMessage()]);
return $this->fallback->quote($cart);
}
return new Quote($r['subtotal_minor'], [], $r['discount_minor'], $r['total_minor']);
}
private function toWire(Cart $c): array
{
return [
'segment' => $c->segment,
'coupon' => $c->coupon,
'now_unix' => $c->now->getTimestamp(),
'lines' => array_map(fn (Line $l) => [
'sku' => $l->sku, 'category' => $l->category, 'qty' => $l->qty, 'unit_minor' => $l->unit,
], $c->lines),
];
}
}
// app/Providers/AppServiceProvider.php::register() — the switch is one line of configuration:
// $this->app->bind(Pricer::class, fn ($app) => config('pricing.remote_url')
// ? new RemotePricer(config('pricing.remote_url'), new LocalPricer($app->make(PricingEngine::class)))
// : new LocalPricer($app->make(PricingEngine::class)));Mechanics
The selection worksheet Must-know
One page per decision. Copy it into the ADR.
| Field | Fill in |
|---|---|
| Problem (one sentence, no pattern name) | |
| Forces (what changes, who, how often, what must not change) | |
| Plain-code option and its cost | |
| Candidate A, B (and C) | |
| Consequences of each: classes, indirection, tests, vocabulary | |
| Next change we can name | |
| Choice and the reason it is the simplest | |
| Review trigger (what event reopens it) |
Measuring pattern density Important
Three cheap numbers, from the shell. They flag places to look; they do not prove anything.
# 1. Interfaces with a single implementation (Go): count interface types, then count implementers by hand.
grep -rn "type .* interface" --include=*.go . | wc -l
# 2. Pattern words in type names, the "decoration" signal.
grep -rEn "type [A-Za-z]*(Manager|Factory|Helper|Impl|Strategy|Handler)\b" --include=*.go . | wc -l
# 3. Files that change together (change coupling) over the last 6 months.
git log --since="6 months ago" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20| Number | Reading | Action |
|---|---|---|
| Many interfaces, few implementers | Speculative generality | Inline the ones with one implementer and no test seam |
| Many pattern words per package | Naming by decoration | Rename by role |
| Two files always change together across an interface | The interface does not hide anything | Merge, or move the change point |
The refactoring loop Good to know
Red, green, refactor. At the refactor step ask three questions: which smell is present, which move answers it, and is the destination a pattern or just simpler plain code? Often it is the second.
Specification as SQL: when the rule must run in the database Important
An in-memory Specification and a SQL query are two implementations of the same question. When the candidate set is large, translate the specification to a WHERE clause (an Eloquent scope in Laravel, a query function in Go) and keep the in-memory version for tests and for single-cart evaluation. Rules stored for the case study live in a table with exactly one active version:
CREATE TABLE discount_rule_sets (
id bigserial PRIMARY KEY,
version integer NOT NULL,
definition jsonb NOT NULL, -- the Def tree: kind, id, params, children
active boolean NOT NULL DEFAULT false,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (version)
);
-- At most one active rule set. A partial unique index on a constant enforces it.
CREATE UNIQUE INDEX discount_rule_sets_one_active
ON discount_rule_sets ((true)) WHERE active;
-- Activate version 12 atomically: deactivate the old one and activate the new one in one transaction.
BEGIN;
UPDATE discount_rule_sets SET active = false WHERE active;
UPDATE discount_rule_sets SET active = true WHERE version = 12;
COMMIT;Go
Before
One function with one switch. Every new customer kind edits it, and an unknown kind silently gets no discount.
// Package before is the starting point: one function, one growing switch.
package before
// Discount returns the discount in cents. Every new customer type edits this function.
func Discount(kind string, subtotal int64, years int) int64 {
switch kind {
case "regular":
return 0
case "vip":
return subtotal * 15 / 100
case "loyal":
pct := int64(years)
if pct > 10 {
pct = 10
}
return subtotal * pct / 100
case "staff":
return subtotal * 30 / 100
default:
return 0
}
}After
A func type as the Strategy, a map as the registry, a creation function that rejects unknown kinds. No new interface per variant, because Go lets a func satisfy the one-method interface.
// Package after applies Replace Conditional Logic with Strategy, step by step.
package after
import "fmt"
// Customer carries the inputs the strategies need.
type Customer struct {
Kind string
Years int
}
// Discounter is the Strategy interface (the point of variation).
type Discounter interface {
Discount(c Customer, subtotal int64) int64
}
// DiscounterFunc adapts a function to Discounter.
type DiscounterFunc func(Customer, int64) int64
// Discount calls the function.
func (f DiscounterFunc) Discount(c Customer, s int64) int64 { return f(c, s) }
func percent(p int64) Discounter {
return DiscounterFunc(func(_ Customer, s int64) int64 { return s * p / 100 })
}
var strategies = map[string]Discounter{
"regular": percent(0),
"vip": percent(15),
"staff": percent(30),
"loyal": DiscounterFunc(func(c Customer, s int64) int64 {
return s * int64(min(c.Years, 10)) / 100
}),
}
// For is the creation point (Introduce Polymorphic Creation). An unknown kind is an error, not a silent zero.
func For(kind string) (Discounter, error) {
d, ok := strategies[kind]
if !ok {
return nil, fmt.Errorf("unknown customer kind %q", kind)
}
return d, nil
}The Go angle
Go makes several patterns small enough to be invisible:
| Pattern | Go idiom | Why it is small in Go |
|---|---|---|
| Strategy | A func type or a one-method interface | Any function can satisfy an interface via a func type |
| Adapter | HandlerFunc | Methods on func types |
| Decorator | func(Handler) Handler | First-class functions, implicit interfaces |
| Observer | A slice of funcs, or a channel | No framework needed |
| Singleton | A package-level variable (use sparingly) | Usually an injected value instead |
| Factory | A constructor function NewX, or a map of constructors | No classes |
| Builder | Functional options or a fluent struct | Optional parameters are the common case |
| Visitor | A type switch | Closed sets of types fit a switch |
The standard library teaches the style: http.Handler is one method; sort.Interface is three; io.Reader is one. Small interfaces defined where they are used keep patterns light (see ISP). The complete case study below is a Go package with six small files and no framework.
Laravel
Before
A match on a string inside a service. The same shape as the Go "before".
<?php
// app/Services/CustomerDiscount.php — starting point: one growing match.
namespace App\Services;
final class CustomerDiscount
{
public function for(string $kind, int $subtotal, int $years): int
{
return match ($kind) {
'regular' => 0,
'vip' => intdiv($subtotal * 15, 100),
'loyal' => intdiv($subtotal * min($years, 10), 100),
'staff' => intdiv($subtotal * 30, 100),
default => 0, // a typo in $kind silently gives no discount
};
}
}After
Container-tagged strategies and one factory class. Adding a customer kind is one new class and one name in a service-provider list.
<?php
// Replace Conditional Logic with Strategy: one class per variant, one place that creates them.
namespace App\Discounts;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
interface Discounter
{
public function kind(): string;
public function discount(int $subtotal, int $years): int;
}
final class Vip implements Discounter
{
public function kind(): string { return 'vip'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * 15, 100); }
}
final class Loyal implements Discounter
{
public function kind(): string { return 'loyal'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * min($years, 10), 100); }
}
// Creation point: the container injects every class tagged 'discounters' (see the service provider below).
final class DiscounterFactory
{
/** @var array<string, Discounter> */
private array $byKind = [];
/** @param iterable<Discounter> $discounters */
public function __construct(#[Tag('discounters')] iterable $discounters)
{
foreach ($discounters as $d) {
$this->byKind[$d->kind()] = $d;
}
}
public function for(string $kind): Discounter
{
return $this->byKind[$kind] ?? throw new InvalidArgumentException("unknown customer kind [$kind]");
}
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->tag([Vip::class, Loyal::class], 'discounters');
// A new customer kind is a new class plus one name in that list; DiscounterFactory never changes.The Laravel angle
Laravel ships most of the catalogue as extension points, so the first question is "does the framework already have this?"
| Need | Framework answer | Pattern underneath |
|---|---|---|
| Pick an implementation by name | Manager subclass, driver(), extend() | Factory + Strategy |
| Wrap behaviour around a request | HTTP middleware, Pipeline | Decorator + Chain |
| React to a fact | Event::listen, model observers | Observer + Mediator |
| Several channels | Notification channels, Notification::extend | Strategy per channel |
| Swap storage | Storage disks, Storage::extend | Adapter over Flysystem |
| Build a query | Query builder, scopes | Builder + Composite (nested wheres) |
| Resolve dependencies | Container, contextual binding, tags | Factory + Registry |
| Group similar implementations | $this->app->tag([...], 'name'), #[Tag('name')] | Registry |
The case study below uses the container for wiring only; the rules themselves are plain PHP and need no framework to test.
Case study: a pricing and discount engine
The requirements
- Marketing defines rules (percent off, fixed amount, buy X get Y) and changes them weekly without a deploy.
- Rules have conditions: customer segment, minimum subtotal, a date window, a category, a coupon.
- Rules combine: some stack, some are "best of", some are "first that applies", and groups nest.
- The quote must be exact (money in minor units), reproducible (same cart, same quote) and explainable (each discount has a reason).
- A policy cap limits the total discount; the total never goes below zero.
- Support staff must see which rule gave which discount.
Forces
| Force | Pattern it points to |
|---|---|
| New rule kinds arrive every month, from one team today | Strategy with a registry Factory |
| Rules combine in trees with three combine modes | Composite |
| Conditions combine freely (and, or, not) and are reused | Specification |
| Rule definitions are stored data | Factory building from a Def |
| Quotes must be reproducible and testable | Pure rules, clock inside the cart |
| Pricing may become its own service later | A port with an in-process adapter |
Candidates and consequences
| Candidate | Cost | Verdict |
|---|---|---|
One function with switch on rule kind | Cheap; every new kind edits one hot file; no nesting | Rejected: rule kinds change monthly and nest |
| Strategy only (flat list of rules) | One type per kind | Not enough: no groups or combine modes |
| Strategy + Composite | Trees, modes | Chosen core |
| Add Specification for conditions | One small interface plus combinators | Chosen: conditions repeat across kinds |
| Registry Factory from JSON | One map, one Build | Chosen: marketing edits data |
| Rules as a scripting language (Interpreter) | A parser, a sandbox, security review | Rejected for now (see decision log D6) |
| Event-sourced quotes | Heavy | Rejected: a quote is a pure function, not a history |
The picture is the design. Engine depends on Rule only. Leaf rules hold a Spec in When. Group is a Rule that holds rules (the composite). Factory turns a stored Def tree into a Rule tree.
Decision log
| ID | Decision | Alternatives | Reason | Review trigger |
|---|---|---|---|---|
| D1 | Money is int64 minor units | float64, decimal library | Exactness; no rounding surprises | Multi-currency with sub-minor units |
| D2 | Rule is a two-method interface (Name, Apply), pure | Rules with side effects | Testable, reproducible | A rule needs external data (then pass it in Cart) |
| D3 | Group with three modes | Separate classes per mode | One composite, small switch | A fourth mode needs state |
| D4 | Conditions are Spec values | Fields on each rule | Reuse and combine | Specs needed in SQL queries |
| D5 | Factory is a registry (Register(kind, ctor)) | switch on kind | New kind without editing the factory | Kinds must be unique across plugins |
| D6 | No scripting language | Interpreter pattern | No sandbox to maintain | Marketing needs formulas, not parameters |
| D7 | Clock lives in Cart.Now | time.Now() in rules | Deterministic tests | None |
| D8 | Global cap is a policy in Engine, not a rule | Cap as a rule | Cap must apply after all rules | Per-segment caps |
| D9 | Unknown kind or bad params fail at load | Skip silently | A wrong price is worse than no deploy | None |
| D10 | Pricer port with Local and Remote adapters | Call the engine directly | Future extraction costs one adapter | Service extracted |
Go implementation
The Go module is academy/patterns-in-practice, package pricing. Cart and money:
// Package pricing is the case-study discount engine: Strategy + Composite + Factory + Specification.
package pricing
import "time"
// Money is an amount in minor units (cents). Never use float64 for money.
type Money int64
// Line is one cart line.
type Line struct {
SKU string
Category string
Qty int
Unit Money
}
// Total is the undiscounted line total.
func (l Line) Total() Money { return l.Unit * Money(l.Qty) }
// Cart is the input of the engine. It carries Now so rules never call time.Now.
type Cart struct {
Lines []Line
Segment string // "new", "regular", "vip"
Coupon string
Now time.Time
}
// Subtotal sums all lines.
func (c Cart) Subtotal() Money {
var s Money
for _, l := range c.Lines {
s += l.Total()
}
return s
}
// CategoryTotal sums the lines of one category.
func (c Cart) CategoryTotal(category string) Money {
var s Money
for _, l := range c.Lines {
if l.Category == category {
s += l.Total()
}
}
return s
}Specification (the combinators are the pattern):
package pricing
import "time"
// Spec is the Specification pattern: a named, combinable yes/no question about a cart.
type Spec interface {
IsSatisfiedBy(Cart) bool
}
// SpecFunc adapts a function to Spec.
type SpecFunc func(Cart) bool
// IsSatisfiedBy calls the function.
func (f SpecFunc) IsSatisfiedBy(c Cart) bool { return f(c) }
// Always matches every cart.
var Always Spec = SpecFunc(func(Cart) bool { return true })
// And requires every spec to hold.
func And(specs ...Spec) Spec {
return SpecFunc(func(c Cart) bool {
for _, s := range specs {
if !s.IsSatisfiedBy(c) {
return false
}
}
return true
})
}
// Or requires at least one spec to hold.
func Or(specs ...Spec) Spec {
return SpecFunc(func(c Cart) bool {
for _, s := range specs {
if s.IsSatisfiedBy(c) {
return true
}
}
return false
})
}
// Not negates a spec.
func Not(s Spec) Spec { return SpecFunc(func(c Cart) bool { return !s.IsSatisfiedBy(c) }) }
// MinSubtotal holds when the cart subtotal reaches min.
func MinSubtotal(min Money) Spec {
return SpecFunc(func(c Cart) bool { return c.Subtotal() >= min })
}
// InSegment holds for one customer segment.
func InSegment(segment string) Spec {
return SpecFunc(func(c Cart) bool { return c.Segment == segment })
}
// HasCategory holds when any line belongs to the category.
func HasCategory(category string) Spec {
return SpecFunc(func(c Cart) bool { return c.CategoryTotal(category) > 0 })
}
// Between holds inside the half-open window [from, to).
func Between(from, to time.Time) Spec {
return SpecFunc(func(c Cart) bool { return !c.Now.Before(from) && c.Now.Before(to) })
}
// WithCoupon holds when the cart carries the coupon code.
func WithCoupon(code string) Spec {
return SpecFunc(func(c Cart) bool { return c.Coupon == code })
}Strategy: the rules.
package pricing
// Adjustment is one discount line in the quote. Amount is positive and is subtracted.
type Adjustment struct {
Rule string
Amount Money
Reason string
}
// Rule is the Strategy: one pricing algorithm behind one method.
// Apply must be pure: same cart, same adjustments, no I/O, no clock.
type Rule interface {
Name() string
Apply(Cart) []Adjustment
}
// PercentOff discounts a percentage of the subtotal (or of one category) when When holds.
type PercentOff struct {
ID string
When Spec
Percent int // 0..100
Category string // empty means the whole cart
}
// Name returns the rule id.
func (r PercentOff) Name() string { return r.ID }
// Apply computes the percentage discount with integer math (floor).
func (r PercentOff) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) {
return nil
}
base := c.Subtotal()
if r.Category != "" {
base = c.CategoryTotal(r.Category)
}
amount := base * Money(r.Percent) / 100
if amount <= 0 {
return nil
}
return []Adjustment{{Rule: r.ID, Amount: amount, Reason: "percent off"}}
}
// FixedOff subtracts a fixed amount, never more than the subtotal.
type FixedOff struct {
ID string
When Spec
Amount Money
}
// Name returns the rule id.
func (r FixedOff) Name() string { return r.ID }
// Apply returns one adjustment capped by the subtotal.
func (r FixedOff) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) {
return nil
}
amount := min(r.Amount, c.Subtotal())
if amount <= 0 {
return nil
}
return []Adjustment{{Rule: r.ID, Amount: amount, Reason: "fixed off"}}
}
// BuyXGetY gives the cheapest free unit in every complete group of Buy+Get units of one SKU.
type BuyXGetY struct {
ID string
When Spec
SKU string
Buy int
Get int
}
// Name returns the rule id.
func (r BuyXGetY) Name() string { return r.ID }
// Apply gives Get free units per Buy+Get units.
func (r BuyXGetY) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) || r.Buy <= 0 || r.Get <= 0 {
return nil
}
var out []Adjustment
for _, l := range c.Lines {
if l.SKU != r.SKU {
continue
}
free := l.Qty / (r.Buy + r.Get) * r.Get
if free > 0 {
out = append(out, Adjustment{Rule: r.ID, Amount: l.Unit * Money(free), Reason: "free units"})
}
}
return out
}Composite: the group.
package pricing
// Mode says how a Group combines the adjustments of its children.
type Mode int
const (
// Stack applies every child (all discounts add up).
Stack Mode = iota
// Best applies only the child with the largest total discount.
Best
// First applies the first child that produces any discount.
First
)
// Group is the Composite: a Rule made of Rules. A Group can contain Groups.
type Group struct {
ID string
Mode Mode
Children []Rule
}
// Name returns the group id.
func (g Group) Name() string { return g.ID }
// Apply combines child results according to Mode.
func (g Group) Apply(c Cart) []Adjustment {
switch g.Mode {
case First:
for _, ch := range g.Children {
if adj := ch.Apply(c); len(adj) > 0 {
return adj
}
}
return nil
case Best:
var best []Adjustment
var bestTotal Money
for _, ch := range g.Children {
adj := ch.Apply(c)
if t := sum(adj); t > bestTotal {
best, bestTotal = adj, t
}
}
return best
default:
var all []Adjustment
for _, ch := range g.Children {
all = append(all, ch.Apply(c)...)
}
return all
}
}
func sum(adj []Adjustment) Money {
var s Money
for _, a := range adj {
s += a.Amount
}
return s
}Factory: the registry and the stored definition.
package pricing
import (
"encoding/json"
"fmt"
"time"
)
// Def is the stored, data-only description of a rule (a JSON row in the database).
type Def struct {
Kind string `json:"kind"`
ID string `json:"id"`
Params json.RawMessage `json:"params,omitempty"`
Segment string `json:"segment,omitempty"`
MinTotal Money `json:"min_total,omitempty"`
From *time.Time `json:"from,omitempty"`
To *time.Time `json:"to,omitempty"`
Children []Def `json:"children,omitempty"`
}
// Constructor builds one kind of rule from a Def.
type Constructor func(f *Factory, d Def) (Rule, error)
// Factory is a registry-based factory: new kinds are added with Register, never by editing a switch.
type Factory struct {
kinds map[string]Constructor
}
// NewFactory returns a factory with the built-in kinds registered.
func NewFactory() *Factory {
f := &Factory{kinds: map[string]Constructor{}}
f.Register("percent_off", percentOff)
f.Register("fixed_off", fixedOff)
f.Register("buy_x_get_y", buyXGetY)
f.Register("group", group)
return f
}
// Register adds or replaces a kind.
func (f *Factory) Register(kind string, c Constructor) { f.kinds[kind] = c }
// Build creates a rule tree from a definition tree.
func (f *Factory) Build(d Def) (Rule, error) {
c, ok := f.kinds[d.Kind]
if !ok {
return nil, fmt.Errorf("pricing: unknown rule kind %q (rule %q)", d.Kind, d.ID)
}
return c(f, d)
}
// whenOf turns the common Def fields into a Specification.
func whenOf(d Def) Spec {
specs := []Spec{}
if d.Segment != "" {
specs = append(specs, InSegment(d.Segment))
}
if d.MinTotal > 0 {
specs = append(specs, MinSubtotal(d.MinTotal))
}
if d.From != nil && d.To != nil {
specs = append(specs, Between(*d.From, *d.To))
}
if len(specs) == 0 {
return Always
}
return And(specs...)
}
func percentOff(_ *Factory, d Def) (Rule, error) {
var p struct {
Percent int `json:"percent"`
Category string `json:"category"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.Percent <= 0 || p.Percent > 100 {
return nil, fmt.Errorf("pricing: rule %q: percent must be 1..100, got %d", d.ID, p.Percent)
}
return PercentOff{ID: d.ID, When: whenOf(d), Percent: p.Percent, Category: p.Category}, nil
}
func fixedOff(_ *Factory, d Def) (Rule, error) {
var p struct {
Amount Money `json:"amount"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.Amount <= 0 {
return nil, fmt.Errorf("pricing: rule %q: amount must be positive", d.ID)
}
return FixedOff{ID: d.ID, When: whenOf(d), Amount: p.Amount}, nil
}
func buyXGetY(_ *Factory, d Def) (Rule, error) {
var p struct {
SKU string `json:"sku"`
Buy int `json:"buy"`
Get int `json:"get"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.SKU == "" || p.Buy <= 0 || p.Get <= 0 {
return nil, fmt.Errorf("pricing: rule %q: sku, buy and get are required", d.ID)
}
return BuyXGetY{ID: d.ID, When: whenOf(d), SKU: p.SKU, Buy: p.Buy, Get: p.Get}, nil
}
func group(f *Factory, d Def) (Rule, error) {
var p struct {
Mode string `json:"mode"`
}
if len(d.Params) > 0 {
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: group %q: %w", d.ID, err)
}
}
modes := map[string]Mode{"": Stack, "stack": Stack, "best": Best, "first": First}
mode, ok := modes[p.Mode]
if !ok {
return nil, fmt.Errorf("pricing: group %q: unknown mode %q", d.ID, p.Mode)
}
g := Group{ID: d.ID, Mode: mode}
for _, cd := range d.Children {
child, err := f.Build(cd)
if err != nil {
return nil, err
}
g.Children = append(g.Children, child)
}
return g, nil
}The engine and its guard rails:
package pricing
// Quote is the result of pricing a cart.
type Quote struct {
Subtotal Money
Adjustments []Adjustment
Discount Money
Total Money
}
// Engine runs the root rule and applies the global guard rails.
type Engine struct {
Root Rule
// MaxDiscountPercent caps the total discount (policy, not a rule). 0 means no cap.
MaxDiscountPercent int
}
// Price returns a quote. It never returns a negative total.
func (e Engine) Price(c Cart) Quote {
q := Quote{Subtotal: c.Subtotal()}
if e.Root != nil {
q.Adjustments = e.Root.Apply(c)
}
q.Discount = sum(q.Adjustments)
if e.MaxDiscountPercent > 0 {
if limit := q.Subtotal * Money(e.MaxDiscountPercent) / 100; q.Discount > limit {
q.Discount = limit
}
}
q.Discount = min(q.Discount, q.Subtotal)
q.Total = q.Subtotal - q.Discount
return q
}Tests:
package pricing
import (
"encoding/json"
"testing"
"time"
)
var now = time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
func cart(segment string, lines ...Line) Cart {
return Cart{Lines: lines, Segment: segment, Now: now}
}
func TestSpecifications(t *testing.T) {
c := cart("vip", Line{SKU: "tv", Category: "electronics", Qty: 1, Unit: 50000})
cases := []struct {
name string
spec Spec
want bool
}{
{"vip segment", InSegment("vip"), true},
{"min subtotal not met", MinSubtotal(60000), false},
{"and", And(InSegment("vip"), HasCategory("electronics")), true},
{"or", Or(InSegment("new"), MinSubtotal(1)), true},
{"not", Not(InSegment("vip")), false},
{"window open", Between(now.Add(-time.Hour), now.Add(time.Hour)), true},
{"window end is exclusive", Between(now.Add(-time.Hour), now), false},
}
for _, tc := range cases {
if got := tc.spec.IsSatisfiedBy(c); got != tc.want {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
}
}
}
func TestRulesArePure(t *testing.T) {
c := cart("regular", Line{SKU: "a", Category: "books", Qty: 3, Unit: 1000})
r := PercentOff{ID: "ten", When: Always, Percent: 10}
first, second := r.Apply(c), r.Apply(c)
if len(first) != 1 || first[0].Amount != 300 || second[0].Amount != 300 {
t.Fatalf("unexpected adjustments: %v %v", first, second)
}
}
func TestBuyXGetY(t *testing.T) {
c := cart("regular", Line{SKU: "mug", Qty: 7, Unit: 500})
adj := BuyXGetY{ID: "b2g1", When: Always, SKU: "mug", Buy: 2, Get: 1}.Apply(c)
if len(adj) != 1 || adj[0].Amount != 1000 { // 7 / 3 = 2 free units
t.Fatalf("got %v", adj)
}
}
func TestGroupModes(t *testing.T) {
c := cart("vip", Line{SKU: "a", Qty: 1, Unit: 10000})
ten := PercentOff{ID: "ten", When: Always, Percent: 10}
vip := PercentOff{ID: "vip", When: InSegment("vip"), Percent: 15}
cases := []struct {
name string
mode Mode
want Money
}{
{"stack", Stack, 2500},
{"best", Best, 1500},
{"first", First, 1000},
}
for _, tc := range cases {
g := Group{ID: tc.name, Mode: tc.mode, Children: []Rule{ten, vip}}
if got := sum(g.Apply(c)); got != tc.want {
t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
}
}
}
const rulesJSON = `{
"kind": "group", "id": "root", "params": {"mode": "stack"},
"children": [
{"kind": "percent_off", "id": "vip15", "segment": "vip", "params": {"percent": 15}},
{"kind": "group", "id": "coupons", "params": {"mode": "best"}, "children": [
{"kind": "fixed_off", "id": "welcome", "min_total": 5000, "params": {"amount": 700}},
{"kind": "percent_off", "id": "books5", "params": {"percent": 5, "category": "books"}}
]}
]
}`
func TestFactoryBuildsTreeAndEngineQuotes(t *testing.T) {
var def Def
if err := json.Unmarshal([]byte(rulesJSON), &def); err != nil {
t.Fatal(err)
}
root, err := NewFactory().Build(def)
if err != nil {
t.Fatal(err)
}
c := cart("vip", Line{SKU: "novel", Category: "books", Qty: 2, Unit: 4000})
q := Engine{Root: root}.Price(c)
// subtotal 8000; vip15 = 1200; best of welcome(700) and books5(400) = 700
if q.Subtotal != 8000 || q.Discount != 1900 || q.Total != 6100 {
t.Fatalf("unexpected quote: %+v", q)
}
}
func TestFactoryRejectsBadDefinitions(t *testing.T) {
f := NewFactory()
bad := []Def{
{Kind: "nope", ID: "x"},
{Kind: "percent_off", ID: "p", Params: json.RawMessage(`{"percent": 150}`)},
{Kind: "group", ID: "g", Params: json.RawMessage(`{"mode": "random"}`)},
}
for _, d := range bad {
if _, err := f.Build(d); err == nil {
t.Errorf("rule %q: expected an error", d.ID)
}
}
}
func TestEngineGuardRails(t *testing.T) {
c := cart("vip", Line{SKU: "a", Qty: 1, Unit: 1000})
e := Engine{
Root: Group{ID: "all", Mode: Stack, Children: []Rule{
PercentOff{ID: "a", When: Always, Percent: 80},
PercentOff{ID: "b", When: Always, Percent: 80},
}},
MaxDiscountPercent: 50,
}
if q := e.Price(c); q.Discount != 500 || q.Total != 500 {
t.Fatalf("cap not applied: %+v", q)
}
if q := (Engine{}).Price(c); q.Total != 1000 {
t.Fatalf("empty engine must not discount: %+v", q)
}
}Laravel implementation
The same design in PHP 8.4 and Laravel 13. The rules and specifications are plain classes; only the service provider touches the framework.
<?php
// app/Pricing/Cart.php — input of the engine. Money is an integer in minor units (cents).
namespace App\Pricing;
use DateTimeImmutable;
final readonly class Line
{
public function __construct(
public string $sku,
public string $category,
public int $qty,
public int $unit,
) {}
public function total(): int
{
return $this->unit * $this->qty;
}
}
final readonly class Cart
{
/** @param list<Line> $lines */
public function __construct(
public array $lines,
public string $segment,
public DateTimeImmutable $now,
public ?string $coupon = null,
) {}
public function subtotal(): int
{
return array_sum(array_map(fn (Line $l) => $l->total(), $this->lines));
}
public function categoryTotal(string $category): int
{
return array_sum(array_map(
fn (Line $l) => $l->category === $category ? $l->total() : 0,
$this->lines,
));
}
}<?php
// app/Pricing/Specification.php — the Specification pattern: combinable yes/no questions about a cart.
namespace App\Pricing;
use Closure;
use DateTimeImmutable;
interface Specification
{
public function isSatisfiedBy(Cart $cart): bool;
}
final readonly class Spec implements Specification
{
private function __construct(private Closure $test) {}
public static function always(): self
{
return new self(fn () => true);
}
public static function segment(string $segment): self
{
return new self(fn (Cart $c) => $c->segment === $segment);
}
public static function minSubtotal(int $min): self
{
return new self(fn (Cart $c) => $c->subtotal() >= $min);
}
public static function hasCategory(string $category): self
{
return new self(fn (Cart $c) => $c->categoryTotal($category) > 0);
}
/** Half-open window [from, to). */
public static function between(DateTimeImmutable $from, DateTimeImmutable $to): self
{
return new self(fn (Cart $c) => $c->now >= $from && $c->now < $to);
}
public static function and(Specification ...$specs): self
{
return new self(fn (Cart $c) => array_all($specs, fn (Specification $s) => $s->isSatisfiedBy($c)));
}
public static function or(Specification ...$specs): self
{
return new self(fn (Cart $c) => array_any($specs, fn (Specification $s) => $s->isSatisfiedBy($c)));
}
public static function not(Specification $spec): self
{
return new self(fn (Cart $c) => ! $spec->isSatisfiedBy($c));
}
public function isSatisfiedBy(Cart $cart): bool
{
return ($this->test)($cart);
}
}<?php
// app/Pricing/Rules.php — Strategy (PricingRule) and Composite (RuleGroup).
namespace App\Pricing;
final readonly class Adjustment
{
public function __construct(public string $rule, public int $amount, public string $reason) {}
}
/** The Strategy. apply() must be pure: no I/O, no now(), no randomness. */
interface PricingRule
{
public function name(): string;
/** @return list<Adjustment> */
public function apply(Cart $cart): array;
}
final readonly class PercentOff implements PricingRule
{
public function __construct(
private string $id,
private Specification $when,
private int $percent,
private string $category = '',
) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
if (! $this->when->isSatisfiedBy($cart)) {
return [];
}
$base = $this->category === '' ? $cart->subtotal() : $cart->categoryTotal($this->category);
$amount = intdiv($base * $this->percent, 100);
return $amount > 0 ? [new Adjustment($this->id, $amount, 'percent off')] : [];
}
}
final readonly class FixedOff implements PricingRule
{
public function __construct(private string $id, private Specification $when, private int $amount) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
if (! $this->when->isSatisfiedBy($cart)) {
return [];
}
$amount = min($this->amount, $cart->subtotal());
return $amount > 0 ? [new Adjustment($this->id, $amount, 'fixed off')] : [];
}
}
enum Mode: string
{
case Stack = 'stack'; // every child applies
case Best = 'best'; // only the largest discount applies
case First = 'first'; // the first child that discounts wins
}
/** The Composite: a rule made of rules. A group may contain groups. */
final readonly class RuleGroup implements PricingRule
{
/** @param list<PricingRule> $children */
public function __construct(private string $id, private Mode $mode, private array $children) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
return match ($this->mode) {
Mode::Stack => array_merge(...array_map(fn (PricingRule $r) => $r->apply($cart), $this->children)) ?: [],
Mode::First => $this->first($cart),
Mode::Best => $this->best($cart),
};
}
private function first(Cart $cart): array
{
foreach ($this->children as $child) {
if ($adjustments = $child->apply($cart)) {
return $adjustments;
}
}
return [];
}
private function best(Cart $cart): array
{
$best = [];
$bestTotal = 0;
foreach ($this->children as $child) {
$adjustments = $child->apply($cart);
$total = array_sum(array_map(fn (Adjustment $a) => $a->amount, $adjustments));
if ($total > $bestTotal) {
[$best, $bestTotal] = [$adjustments, $total];
}
}
return $best;
}
}<?php
// app/Pricing/RuleFactory.php — registry-based Factory: kinds are added with register(), never by editing a match.
namespace App\Pricing;
use DateTimeImmutable;
use InvalidArgumentException;
final class RuleFactory
{
/** @var array<string, callable(array, self): PricingRule> */
private array $kinds = [];
public function __construct()
{
$this->register('percent_off', fn (array $d) => new PercentOff(
$d['id'], self::when($d), $this->percent($d), $d['params']['category'] ?? '',
));
$this->register('fixed_off', fn (array $d) => new FixedOff(
$d['id'], self::when($d), $this->positive($d, 'amount'),
));
$this->register('group', function (array $d, self $f) {
$mode = Mode::tryFrom($d['params']['mode'] ?? 'stack')
?? throw new InvalidArgumentException("group {$d['id']}: unknown mode");
return new RuleGroup($d['id'], $mode, array_map($f->build(...), $d['children'] ?? []));
});
}
public function register(string $kind, callable $constructor): void
{
$this->kinds[$kind] = $constructor;
}
/** @param array<string, mixed> $definition decoded JSON from the discount_rules table */
public function build(array $definition): PricingRule
{
$make = $this->kinds[$definition['kind'] ?? ''] ?? throw new InvalidArgumentException(
sprintf('unknown rule kind "%s" (rule "%s")', $definition['kind'] ?? '', $definition['id'] ?? '?'),
);
return $make($definition, $this);
}
private static function when(array $d): Specification
{
$specs = [];
if (! empty($d['segment'])) {
$specs[] = Spec::segment($d['segment']);
}
if (! empty($d['min_total'])) {
$specs[] = Spec::minSubtotal((int) $d['min_total']);
}
if (! empty($d['from']) && ! empty($d['to'])) {
$specs[] = Spec::between(new DateTimeImmutable($d['from']), new DateTimeImmutable($d['to']));
}
return $specs === [] ? Spec::always() : Spec::and(...$specs);
}
private function percent(array $d): int
{
$p = (int) ($d['params']['percent'] ?? 0);
return ($p >= 1 && $p <= 100) ? $p : throw new InvalidArgumentException("rule {$d['id']}: percent must be 1..100");
}
private function positive(array $d, string $key): int
{
$v = (int) ($d['params'][$key] ?? 0);
return $v > 0 ? $v : throw new InvalidArgumentException("rule {$d['id']}: $key must be positive");
}
}<?php
// app/Pricing/PricingEngine.php — runs the root rule and applies the global guard rails.
namespace App\Pricing;
final readonly class Quote
{
/** @param list<Adjustment> $adjustments */
public function __construct(
public int $subtotal,
public array $adjustments,
public int $discount,
public int $total,
) {}
}
final readonly class PricingEngine
{
public function __construct(private PricingRule $root, private int $maxDiscountPercent = 0) {}
public function price(Cart $cart): Quote
{
$subtotal = $cart->subtotal();
$adjustments = $this->root->apply($cart);
$discount = array_sum(array_map(fn (Adjustment $a) => $a->amount, $adjustments));
if ($this->maxDiscountPercent > 0) {
$discount = min($discount, intdiv($subtotal * $this->maxDiscountPercent, 100));
}
$discount = min($discount, $subtotal);
return new Quote($subtotal, $adjustments, $discount, $subtotal - $discount);
}
}<?php
// app/Providers/PricingServiceProvider.php — wiring: the only place that knows the concrete classes.
namespace App\Providers;
use App\Pricing\PricingEngine;
use App\Pricing\RuleFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
final class PricingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(RuleFactory::class);
// Build the rule tree once per process from the active definition (one JSON document per version).
$this->app->singleton(PricingEngine::class, function ($app) {
$json = DB::table('discount_rule_sets')->where('active', true)->value('definition');
$root = $app->make(RuleFactory::class)->build(json_decode($json, true, flags: JSON_THROW_ON_ERROR));
return new PricingEngine($root, maxDiscountPercent: config('pricing.max_discount_percent', 50));
});
}
}<?php
// tests/Unit/PricingEngineTest.php — pure unit tests: no database, no container, no HTTP.
namespace Tests\Unit;
use App\Pricing\Cart;
use App\Pricing\Line;
use App\Pricing\PricingEngine;
use App\Pricing\RuleFactory;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class PricingEngineTest extends TestCase
{
private const RULES = [
'kind' => 'group', 'id' => 'root', 'params' => ['mode' => 'stack'],
'children' => [
['kind' => 'percent_off', 'id' => 'vip15', 'segment' => 'vip', 'params' => ['percent' => 15]],
['kind' => 'group', 'id' => 'coupons', 'params' => ['mode' => 'best'], 'children' => [
['kind' => 'fixed_off', 'id' => 'welcome', 'min_total' => 5000, 'params' => ['amount' => 700]],
['kind' => 'percent_off', 'id' => 'books5', 'params' => ['percent' => 5, 'category' => 'books']],
]],
],
];
private function cart(string $segment, Line ...$lines): Cart
{
return new Cart(array_values($lines), $segment, new DateTimeImmutable('2026-11-27T10:00:00Z'));
}
public function test_factory_builds_the_tree_and_the_engine_quotes(): void
{
$engine = new PricingEngine((new RuleFactory())->build(self::RULES));
$quote = $engine->price($this->cart('vip', new Line('novel', 'books', 2, 4000)));
// subtotal 8000; vip15 = 1200; best of welcome (700) and books5 (400) = 700
$this->assertSame([8000, 1900, 6100], [$quote->subtotal, $quote->discount, $quote->total]);
}
public function test_the_cap_never_lets_the_total_go_below_half(): void
{
$rules = ['kind' => 'group', 'id' => 'all', 'children' => [
['kind' => 'percent_off', 'id' => 'a', 'params' => ['percent' => 80]],
['kind' => 'percent_off', 'id' => 'b', 'params' => ['percent' => 80]],
]];
$engine = new PricingEngine((new RuleFactory())->build($rules), maxDiscountPercent: 50);
$quote = $engine->price($this->cart('regular', new Line('a', 'x', 1, 1000)));
$this->assertSame(500, $quote->total);
}
/** @return iterable<string, array{array<string, mixed>}> */
public static function badDefinitions(): iterable
{
yield 'unknown kind' => [['kind' => 'nope', 'id' => 'x']];
yield 'percent out of range' => [['kind' => 'percent_off', 'id' => 'p', 'params' => ['percent' => 150]]];
yield 'unknown group mode' => [['kind' => 'group', 'id' => 'g', 'params' => ['mode' => 'random']]];
}
#[DataProvider('badDefinitions')]
public function test_the_factory_rejects_bad_definitions(array $definition): void
{
$this->expectException(InvalidArgumentException::class);
(new RuleFactory())->build($definition);
}
}How the design changes over time
Week Change request What changes in code
1 W1 "VIP gets 15%" PercentOff + InSegment spec; one Register
2 W3 "Welcome 7 off from 50 total" FixedOff + MinSubtotal spec; data row only
3 W6 "Black Friday, best of two coupons" Group(Best); window spec; data row only
4 W9 "Buy 2 get 1 on mugs" BuyXGetY type + one Register("buy_x_get_y")
5 W14 "Never discount more than 50%" Engine.MaxDiscountPercent (policy)
6 W20 "Loyalty points" Rules need account data: add it to Cart, not a global
7 W30 "Pricing is its own team" Port + Remote adapter; contract test (migrate)Weeks 1, 2 and 3 change data, not code: that is the payoff of the composite and the registry. Week 6 is the usual temptation to reach into a global; the decision log says add it to the cart so rules stay pure.
Solving the classic problems
| Problem | Preferred pattern language | Cost | Limit |
|---|---|---|---|
A growing switch edited by several people | Map of funcs, then Strategy | One map or one type per variant | Not needed for two stable cases |
| Conditions combine in many ways | Specification | One interface plus combinators | Large candidate sets need SQL |
| Rules form groups | Composite | Tree evaluation cost | Cycles must be prevented |
| Behaviour must wrap calls | Decorator chain | Order sensitivity | Needs a documented order |
| Unknown listeners must react | Observer or events | Hidden control flow | Not for ordered work |
| Third-party extensions | Registry + extend() | Public contract to maintain | Only when third parties exist |
| Swappable infrastructure | Port + Adapter | One adapter per backend | Do not wrap what never changes |
| Undo or audit | Command + Memento | Snapshot size | Large state needs diffs |
| Remote call becomes unreliable | Proxy with timeout and fallback | Degraded answers | Needs a product decision |
| Too many patterns | Inline Class, Collapse Hierarchy | Deleting feels risky | Keep the tests |
Problem: the god switch in checkout
Symptom: a switch on payment kind in the controller, five cases, two teams. Move: Replace Conditional Logic with Strategy, then Manager with extend(). Keep the switch until the third variant.
Problem: the pattern soup
Symptom: every class has a pattern in its name and nobody can say which force it serves. Move: for each type ask "which force?"; if no answer, inline it.
Problem: the untestable singleton
Symptom: tests depend on execution order. Move: inject, and let the container hold the single instance if one is needed.
Choosing: which pattern, or none
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One behaviour, no known variant | Plain function | A comment naming the axis | Cheapest; wait for the force |
| Two variants, one team | switch or map | Table-driven test | Still simple |
| Three or more variants, one team | Strategy by name | Factory function with error on unknown | Variants grow |
| Variants added by other teams | Registry + extend() | Contract test | Open for extension |
| Conditions combine | Specification | And, Or, Not | Reuse |
| Nested groups | Composite | Modes, cycle check | Trees |
| Wrap behaviour | Decorator chain | Order test | Cross-cutting |
| Fan-out of reactions | Events | Outbox if cross-service | Decoupling |
| Operation set on a stable tree | Visitor | Closed set of node types | New operations without edits |
| Unstable tree, stable operations | Methods on nodes | None | Visitor would hurt |
| Hard-to-create object | Builder | Director recipes | Steps and presets |
| Cheap object, simple creation | Constructor | None | No factory needed |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everyday example. A small shop in one Laravel app. Checkout uses Pipeline with three pipes (validate stock, apply discounts, reserve) and a match for two payment kinds. No PaymentManager yet; the second variant is only a match arm. The ADR says "revisit at the third gateway".
Production example. The Go standard library's net/http is a monolith-sized library built from a few small patterns: Handler (Strategy), HandlerFunc (Adapter), StripPrefix and TimeoutHandler (Decorators), ServeMux (Registry). Laravel's own Manager is reused by cache, mail, notifications and filesystems.
Rule of thumb: in a monolith the cheapest pattern is the one you can delete in a single commit.
Modular monolith and multiple databases
Modules own their data and talk through ports. Pricing exposes Pricer; checkout depends only on the port; nothing else imports the rule types (in Go, put them under internal/; in PHP, enforce it with a static dependency check in CI).
| Boundary tool | Pattern | What it protects |
|---|---|---|
| Port (interface owned by the consumer) | DIP, Facade | Consumers from rule internals |
| Module events | Observer | Modules from each other's order of work |
| Read model per module | CQRS-lite | Reports from other modules' tables |
| Wire DTO even in-process | ACL | Domain types from leaking |
Everyday example. Pricing module with Pricer and a Local adapter; reporting module reads quotes through its own view. Production example. A monolith with module boundaries checked in CI, one schema per module, extraction later by replacing Local with Remote (the migrate snippet).
Microservices: patterns with a network in the middle
Which patterns survive is the table in Migrating a feature. The service-scale patterns from the earlier section become real: gateway in front, ACL at each integration, outbox for events, saga for multi-service flows, idempotent consumers.
Step Flow: place an order across three services
1 1 Gateway -> Checkout: POST /orders (Idempotency-Key: k1)
2 2 Checkout -> Pricing: POST /quote (timeout 300 ms, fallback no discount)
3 3 Checkout: INSERT order + outbox row in one local transaction
4 4 Relay -> broker: OrderPlaced (at least once)
5 5 Payment consumer: dedup by event id, charge, emit PaymentCaptured
6 6 Stock consumer: reserve; on failure emit StockFailed
7 7 Checkout (saga step): on StockFailed, cancel order, emit RefundRequestedEveryday example. Checkout calls pricing over HTTP with a fallback; a bad pricing day means no discounts, not no checkout. Production example. The same flow with an outbox table:
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
aggregate_id text NOT NULL,
type text NOT NULL, -- e.g. OrderPlaced
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
-- The relay reads unpublished rows in id order and marks them published after the broker acknowledges.
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;Distributed data: replicas, caches and shared schemas
Patterns meet staleness here.
| Place | Pattern at risk | Failure | Guard |
|---|---|---|---|
| Rule set cached per instance (Flyweight) | Proxy + Flyweight | Instances price differently during rollout | Put rule_set_version in every quote; checkout honours the quote's version |
| Read replica for quotes | Strategy reads data | Replica lag shows old rules | Read rules from the primary or by version |
| Events (Observer) | Observer | Duplicates, reordering | Idempotent consumers, ordering key per aggregate |
| Saga (Mediator) | Command + State | Stuck half-done | Timeouts, compensations, dead-letter queue |
| Singleton | Singleton | Per-process state differs per replica | Use shared storage or none |
Everyday example. A Laravel app with two servers holds the rule tree in a singleton per process; after activating version 12 one server still prices with version 11 until its next boot. Fix: version in the quote and a refresh signal. Production example. Quotes carry rule_set_version; the order stores it; support can recompute the exact discount from the stored version.
Scaling path: 1×, 10×, 100×
| Load | Pattern posture | Change |
|---|---|---|
| 1× (one team, a few rules) | Plain code and a map of funcs | No interfaces yet |
| 10× (several rule kinds, one service) | Strategy + Composite + Specification + Factory | The case study as written |
| 100× (many teams, rules from partners) | Registry with extend(), versioned rule sets, own service, contract tests, caches with version checks | ACL, outbox, saga where needed |
At every step the guiding rule is the same: add a pattern when a named force appears, and write the decision down.
Lab: audit and refactor
Setup: the snippets live in docs/snippets/design/patterns-in-practice/go. All commands run from that directory.
cd docs/snippets/design/patterns-in-practice/go
go vet ./... && go test ./...
# expected: ok for pricing, migrate, combos/decoratorchain, combos/commandmemento- Run the case study.
go test ./pricing -run TestFactoryBuildsTreeAndEngineQuotes -v. Expected: PASS; subtotal 8000, discount 1900, total 6100. - Add a rule kind without editing the factory. In a new file in package
pricing, write aFreeShippingrule and callf.Register("free_shipping", ...)in a test. Expected: the factory builds it;factory.gohas no diff. - Break purity on purpose. In
PercentOff.Apply, addtime.Now()to a condition. Expected:TestSpecificationsand the quote tests become time-dependent; revert and keep the clock inCart.Now. - Count decoration.
grep -rEn "type [A-Za-z]*(Manager|Factory|Helper|Impl)\b" --include=*.go . | wc -l. Expected:Factoryappears once (the registry); nothing else. - Run the contract test.
go test ./migrate -run TestParity -v. Expected: PASS: local and remote adapters agree. Change a percent in only one engine inside the test and see it fail. - Inline an anemic strategy. Open
antipatterns/before/before.go, deleteTaxStrategyandFlatTaxStrategy, addfunc Tax. Expected: nothing else changes; the file shrinks.
Common misconceptions
| Belief | Reality |
|---|---|
| Good design uses many patterns | Good design has the fewest parts that absorb the next change |
| Patterns must be applied up front | Often better reached by refactoring once the second or third variant appears |
| Every interface needs an implementation class per variant | In Go a func type can satisfy the interface; in PHP a closure-based driver is fine |
A factory is always better than new | A factory pays off only when it chooses a type or enforces an invariant |
| Singleton is the right pattern for configuration | The container or an injected value is; a static is a hidden global |
| Observer decouples everything | It hides control flow; ordered work needs explicit orchestration |
| Visitor is the answer to adding operations | Only if the set of node types is stable |
| Microservices need new patterns | They need the same patterns plus timeouts, idempotency and compensation |
| CQRS is a normal default | Fowler: "for most systems CQRS adds risky complexity" |
| ADRs are heavy process | One page, written once, saves the next argument |
Using the framework's Manager is "not clean" | It is the pattern, maintained for you |
Cheat sheet
| Topic | What to remember |
|---|---|
| Selection | Problem, forces, candidates, consequences, simplest that works |
| First candidate | Plain code (function, switch, map) |
| When to add a seam | Third variant, second team, or a slow dependency in tests |
| Factory + Strategy | Name chooses the algorithm; Laravel Manager, Go map of funcs |
| Decorator + Chain | Middleware; each link may stop the chain |
| Command + Memento | Undo; snapshot when no cheap inverse exists |
| Observer + Mediator | Events; unordered reactions only |
| Composite + Visitor | Tree plus operations; Visitor only for stable trees |
| Builder + Director | Steps plus named recipes |
| Proxy + Flyweight | Lazy and shared; immutable objects only |
| Over-engineering signals | One implementation per interface, pattern words in names, factory around new |
| Refactoring | Small steps, tests green, Kerievsky catalogue |
| Service scale | Gateway, ACL, sidecar, outbox, saga: the same ideas with a network |
| Documentation | One-page ADR: context, decision, consequences, review trigger |
| Testing | Role tests, composite tests, factory error tests, wiring test, contract test |
| Extraction | Port first, two adapters, contract test, then route traffic |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are the five steps of the selection method, and which comes before candidates? Important
Answer
Answer: Problem, forces, candidate patterns, consequences, simplest that works. The question "is plain code enough?" comes before any pattern is listed.
2 — Name the four costs Fowler attributes to presumptive features. Good to know
Answer
Answer: Cost of build, cost of delay, cost of carry, cost of repair.
3 — Which two patterns does Illuminate\Support\Manager combine, and where do you add a driver? Important
Answer
Answer: Factory and Strategy. You add a createXxxDriver method in a subclass, or call extend($driver, $callback) at runtime. createDriver() tries custom creators first.
4 — How does Laravel's Pipeline::then() build the chain? Important
Answer
Answer: It runs array_reduce over the reversed pipes with carry(), producing nested closures; each pipe gets the passable and a $next closure.
5 — Give two signs of an anemic strategy and the cure. Important
Answer
Answer: One implementation, no state, no second variant planned. Cure: a plain function; extract an interface when the second variant arrives.
6 — Why is Group a Composite and why does it make the pricing engine data-driven? Important
Answer
Answer: A Group is a Rule that holds Rules, so trees of any shape are one Rule. The Factory builds the tree from stored definitions, so most changes are data rows.
7 — What does Specification separate? Important
Answer
Answer: "how to match a candidate" from the candidate that is matched, so conditions combine and are reusable.
8 — Which patterns survive extraction unchanged, and which turn into network contracts? Important
Answer
Answer: Strategy, Composite, Specification and Factory stay inside the service. Facade becomes the API, Adapter the ACL, Proxy the remote client, Observer events plus outbox, Command a message with an idempotency key, Mediator a saga.
9 — Why does the clock live in Cart.Now? Important
Answer
Answer: So rules are pure and quotes reproducible; tests do not depend on wall-clock time.
10 — What is in an ADR, and how long should it be? Must-know
Answer
Answer: Title, context, decision, status, consequences (all of them), one or two pages (Nygard).
11 — What does a contract test between Local and Remote adapters protect? Important
Answer
Answer: That moving pricing to a service does not change quotes; the two adapters must agree on the same cart.
Glossary
| Term | One line |
|---|---|
| Force | A pressure on the design: a change source, a constraint, a quality goal |
| Consequence | A cost or benefit that follows from a pattern choice |
| Candidate pattern | One of two or three plausible answers to the same forces |
| Simplest that works | The option with the fewest parts that absorbs the next named change |
| Pattern language | A set of patterns that fit one domain and are applied in order |
| Factory + Strategy | A factory picks the algorithm by name; the strategy computes |
| Decorator + Chain | Behaviours that wrap one another, any of which may stop the call |
| Command + Memento | Undoable actions that restore a snapshot when no inverse exists |
| Observer + Mediator | A hub that owns subscriptions so parts never reference each other |
| Composite + Visitor | A tree and operations over it without editing the nodes |
| Builder + Director | Step-by-step construction plus named recipes |
| Proxy + Flyweight | A lazy loader that hands out shared immutable objects |
| Specification | An object that answers "does this candidate match?" and combines with others |
| Strategy | Interchangeable algorithms behind one interface |
| Composite | A tree where a group is used like a single element |
| Registry | A map of names to constructors or instances |
| YAGNI | "You Aren't Gonna Need It": do not build presumptive features |
| Speculative generality | Hooks and abstractions "just in case" |
| Presumptive feature | Fowler's term for code that supports a feature not yet in use |
| Cost of carry | Ongoing complexity from a feature that is not used yet |
| Pattern density | Structure carried per unit of behaviour |
| Singleton abuse | A hidden global instead of an injected dependency |
| Factory explosion | A factory per class by reflex |
| Anemic strategy | A strategy with one body and no variation |
| God mediator | A mediator that holds all rules of all parts |
| Refactoring to patterns | Reaching a pattern by small steps from working code (Kerievsky) |
| ADR | Architecture Decision Record: context, decision, status, consequences |
| Anti-corruption layer (ACL) | An adapter that keeps another model's concepts out of yours |
| Gateway | A single entry point that routes, authenticates and shapes traffic |
| Sidecar | A helper component in a separate process that shares the app's lifecycle |
| Outbox | Messages stored in the same transaction as the data, published later |
| Saga | A coordinated sequence of local transactions with compensations |
| CQRS | Separate models for writing and reading |
| Strangler fig | Gradual replacement behind a routing facade |
| Contract test | A test that two implementations of one port agree |
| Framework pattern | A pattern whose skeleton the framework owns |
| Application pattern | A pattern built for your domain |
References
- Martin Fowler, "Yagni", martinfowler.com, 26 May 2015. martinfowler.com/bliki/Yagni.html
- Michael Nygard, "Documenting Architecture Decisions", 15 November 2011. cognitect.com
- Joshua Kerievsky, Refactoring to Patterns, catalogue of 27 refactorings. industriallogic.com/refactoring-to-patterns/catalog, Replace Conditional Logic with Strategy, Form Template Method, Unify Interfaces with Adapter, Introduce Polymorphic Creation, Extract Composite
- Eric Evans and Martin Fowler, "Specifications". martinfowler.com/apsupp/spec.pdf
- refactoring.guru: Strategy, Decorator, Composite, Memento, Mediator, Flyweight, Speculative Generality. Secondary source for the GoF intents (the GoF book itself was not read for this page).
- Martin Fowler, CQRS, Strangler Fig
- Chris Richardson, Saga, Transactional outbox
- Microsoft Azure Architecture Center: Anti-Corruption Layer, Sidecar, Gateway Routing
- Go source: net/http/server.go, io/io.go, sort/sort.go, database/sql/driver/driver.go
- Laravel framework source (13.x): Container.php, Pipeline.php, Dispatcher.php, Query/Builder.php, ChannelManager.php, FilesystemManager.php, Support/Manager.php, Facades/Pipeline.php
- Laravel 13 docs: Service container, Notifications, Filesystem, Events, Contracts