Code Smells, Anti-Patterns & Refactoring (the 14 smells and their moves)
"Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior." — Martin Fowler, refactoring.com
Summary: A code smell is a quick-to-spot sign that the design may be wrong; a refactoring is a small, named, behaviour-preserving change that fixes it; an anti-pattern is a recurring "solution" that does more harm than good. Focus: Fowler's smell catalogue (1999 and 2018 names) in five families, the 14 smells this chapter drills with Go and Laravel examples, the refactoring moves that cure each one, anti-patterns, architectural smells, tooling, and a full lab with characterization tests. Learning goal: Name the smell in front of you, pick the one move that removes it, take it in a step small enough that the tests stay green, and know when a "smell" is fine and should be left alone.
This page is the complete reference for smells and refactoring. It covers the history (Opdyke, Beck and Fowler, the AntiPatterns book, Kerievsky, Feathers), the whole smell catalogue in both editions' names, the moves from Fowler's 2nd-edition catalogue, anti-patterns from Brown et al., architectural smells, Go and PHP tooling, and what refactoring means when the code is a monolith being split into services. It does not re-teach its neighbours: coupling, cohesion and information hiding are on Design Quality; message chains and the Law of Demeter are on Composing Objects; the five principles that most smells violate are on SOLID (divergent change is the SRP violation; repeated switches are the OCP violation; refused bequest is the LSP violation); named patterns as refactoring targets are on Applying Patterns; and migrating a whole system piece by piece is on Strangler Fig.
Page map
| If you are looking for | Go to |
|---|---|
| The 14 smells, the moves and the timing rules in three tables | Everything in one minute |
| Why we refactor at all, and what it costs | Why refactoring exists |
| Opdyke, Beck, Fowler 1999 and 2018, Brown et al., Kerievsky, Feathers | Where it comes from |
| Definition, small steps, two hats, rule of three, preparatory and litter-pickup refactoring | Refactoring itself |
| All smells in five families, the 1999 and 2018 names side by side | The smell catalogue |
| Long method, large class, primitive obsession ... feature envy, one block each | The 14 smells, one by one |
| Temporary field, message chains, middle man, global data and the rest | The other smells |
| Extract Function, Replace Conditional with Polymorphism, Introduce Special Case and friends | Refactoring moves catalogue |
| God object, lava flow, golden hammer, boat anchor, cargo cult | Anti-patterns |
| Cyclic, hub-like and unstable dependencies, shared database, distributed monolith | Architectural smells |
| The loop, the safety net, commit discipline, large changes | Mechanics |
| gofmt, gopls, golangci-lint, staticcheck, PHPStan, Rector, Pint, PhpStorm | Tooling |
| Fat controller, stringly-typed money, the switch in six files | Solving the classic problems |
| Refactor, rewrite or leave it | Choosing |
| Refactoring a monolith vs extracting a microservice | In architecture |
| A 200-line smelly Go handler and a Laravel controller, step by step with tests | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The 14 smells this chapter drills. The chapter title promises fourteen. The course syllabus we were given names the number but not the list, so these are our choice: the fourteen smells you will meet most in Go services and Laravel apps. Every other smell in Fowler's catalogue is still covered in The other smells.
| # | Smell (refactoring.guru / 1999 name) | Fowler 2018 name | Family | In plain words | First move |
|---|---|---|---|---|---|
| 1 | Long Method | Long Function | Bloaters | One function does many jobs | Extract Function |
| 2 | Large Class | Large Class | Bloaters | One type knows too much | Extract Class |
| 3 | Primitive Obsession | Primitive Obsession | Bloaters | Money as float64, status as a string | Replace Primitive with Object |
| 4 | Long Parameter List | Long Parameter List | Bloaters | Nine arguments, half of them flags | Introduce Parameter Object |
| 5 | Data Clumps | Data Clumps | Bloaters | The same 3–4 values always travel together | Extract Class |
| 6 | Switch Statements | Repeated Switches | OO Abusers | The same switch in several places | Replace Conditional with Polymorphism |
| 7 | Refused Bequest | Refused Bequest | OO Abusers | A subtype that does not want what it inherits | Replace Superclass with Delegate |
| 8 | Divergent Change | Divergent Change | Change Preventers | One module changes for many reasons | Split Phase, Extract Class |
| 9 | Shotgun Surgery | Shotgun Surgery | Change Preventers | One change touches many modules | Move Function, Move Field |
| 10 | Duplicate Code | Duplicated Code | Dispensables | The same logic twice | Extract Function, Pull Up Method |
| 11 | Comments | Comments | Dispensables | A comment explains code that should explain itself | Extract Function, Rename |
| 12 | Data Class | Data Class | Dispensables | Fields and getters, behaviour lives elsewhere | Move Function into it |
| 13 | Speculative Generality | Speculative Generality | Dispensables | Hooks for a future that never came | Collapse Hierarchy, Inline, Remove Dead Code |
| 14 | Feature Envy | Feature Envy | Couplers | A function more interested in another type's data | Move Function |
The moves you will use 90 percent of the time. Names are from Fowler's 2nd-edition catalogue; old names are aliases on the same catalogue card.
| Move | Old name / alias | Cures | Inverse |
|---|---|---|---|
| Extract Function | Extract Method | Long function, comments, duplicate code | Inline Function |
| Extract Variable | Introduce Explaining Variable | Unreadable expressions | Inline Variable |
| Change Function Declaration | Rename Function, Add/Remove Parameter, Change Signature | Mysterious names, speculative parameters | itself |
| Move Function / Move Field | Move Method | Feature envy, shotgun surgery | itself |
| Extract Class | Large class, data clumps, divergent change | Inline Class | |
| Introduce Parameter Object | Long parameter list, data clumps | ||
| Replace Primitive with Object | Replace Data Value with Object, Replace Type Code with Class | Primitive obsession | |
| Replace Conditional with Polymorphism | Repeated switches | ||
| Introduce Special Case | Introduce Null Object | Repeated if x == nil checks | |
| Separate Query from Modifier | Functions that answer and change state |
When to refactor.
| Moment | Name | What you do |
|---|---|---|
| Before a feature | Preparatory refactoring | Make the change easy, then make the easy change |
| While reading code | Comprehension refactoring | Rename and extract until you understand it |
| Passing by | Litter-pickup (camp-site rule) | Leave it a little better than you found it |
| After green in TDD | The refactor step | Clean what you just wrote, tests stay green |
| Third copy of the same thing | Rule of three | First do it, second wince, third refactor |
| A big known problem | Planned / long-term refactoring | A tracked piece of work, done in small releasable steps |
Why refactoring exists
Code that works today still has to change tomorrow. Every change is cheaper when the code says what it does, keeps each decision in one place and lets you test it in isolation. Code drifts away from that shape because features are added under time pressure. Refactoring is the routine that pulls it back, without stopping feature work, by changing structure and never behaviour. Smells tell you where to pull.
Fowler's own case, on the refactoring.com front page: "When a software system is successful, there is always a need to keep enhancing it". Without refactoring, enhancements pile on each other and "new work slows to a crawl."
| Never refactor | Refactor continuously |
|---|---|
| Fast first week | Same speed in week 50 |
| Each change re-reads the whole function | Each change reads one named piece |
| Fixes in one copy miss the other copies | One copy, one fix |
| Tests need the database, the mailer, the clock | Pure rules testable alone |
| Big rewrite every few years | No rewrites; the code evolves |
| Risk: you cannot change it at all | Risk: polishing code nobody will touch again |
The analogy we reuse on this page: a working kitchen. Cooks clean as they go: a knife goes back after use, a spill is wiped now, not at closing. Nobody stops service for a day to "clean the kitchen". A smell is the sticky floor you notice; a refactoring is wiping it; an anti-pattern is the habit that keeps making it sticky (storing the oil on the edge of the counter). A rewrite is closing the restaurant to rebuild the kitchen: sometimes necessary, never the first answer.
Three common misunderstandings, up front
- "Refactoring means any code clean-up, rewrite or redesign." Fowler: "If somebody talks about a system being broken for a couple of days while they are refactoring, you can be pretty sure they are not refactoring." If behaviour changed or the build was red for hours, it was restructuring, not refactoring.
- "A smell means the code is wrong." "smells don't always indicate a problem" (Fowler, CodeSmell). A smell is a reason to look. A 60-line function that parses a protocol frame top to bottom may be the clearest code you can write.
- "Refactoring needs a separate ticket and a sprint." Most refactoring is done minutes before or after a feature, by the person writing it. Only big structural problems need planning, and even those are delivered in small steps.
Where it comes from
Opdyke and Johnson, 1990; Griswold, 1991; Opdyke, 1992. The word "refactoring" in print goes back to William Opdyke and Ralph Johnson's 1990 SOOPPA paper; William Griswold's 1991 thesis studied restructuring of procedural programs, and Opdyke's 1992 thesis, Refactoring Object-Oriented Frameworks, defined behaviour-preserving refactorings for C++ (dates from Wikipedia's Code refactoring article, a secondary source).
Beck and Fowler, 1999. Kent Beck coined "smells" while helping Fowler with the first edition of Refactoring: Improving the Design of Existing Code:
"A code smell is a surface indication that usually corresponds to a deeper problem in the system. The term was first coined by Kent Beck while helping me with my Refactoring book." — Martin Fowler, CodeSmell, bliki, 2006
Chapter 3, "Bad Smells in Code", was written by both, and opens with the warning that no metric will decide for you:
"In our experience, no set of metrics rivals informed human intuition." — Fowler and Beck, Refactoring, 2nd ed., chapter 3 (InformIT excerpt, 2018)
Brown, Malveau, McCormick and Mowbray, 1998. AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis catalogued recurring bad solutions from three viewpoints (developer, architect, manager); the term anti-pattern itself is credited to Andrew Koenig (1995) on Wikipedia (secondary). Its development anti-patterns came from Mike Akroyd, and the authors' site insists each one ships with a way out: "Name the problem, then say how to get out of it."
Kerievsky, 2004. Refactoring to Patterns joined the two worlds: "Refactoring to Patterns suggests that using patterns to improve an existing design is better than using patterns early in a new design." (Industrial Logic book page). Patterns are destinations you refactor toward when a smell asks for one.
Feathers, 2004. Working Effectively with Legacy Code gave us the characterization test: a test that records what the code does now, so you can refactor code that has no tests (Wikipedia credits the term to Feathers; secondary).
Fowler, 2nd edition, 2018. Examples move to JavaScript, the catalogue moves online at refactoring.com/catalog, several refactorings are renamed (Extract Method becomes Extract Function) and the smell list is revised: four new smells, four renamed, two dropped. The full comparison is in the catalogue.
Refactoring itself
Definition: behaviour-preserving, small steps, tests Must-know
In plain words: you change how the code is built, not what it does, in steps so small that it works after every one of them.
Common misunderstanding: "If the end result behaves the same, the path does not matter." The path is the technique. Fowler's front page: "Its heart is a series of small behavior preserving transformations." A two-day rewrite that ends with the same behaviour is not refactoring; it is a gamble that happened to pay.
Definition: Fowler gives two forms on his bliki. Noun: "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior." Verb: "to restructure software by applying a series of refactorings without changing its observable behavior." The safety net is a test suite you run after each step; his rule of thumb from Refactoring Malapropism: "If you are doing refactoring your system should not be broken for more than a few minutes at a time".
Minute Step Tests Commit
1 00 spot: 40-line discount block in handler green
2 02 Extract Function -> discount() green refactor: extract discount
3 05 Extract Variable -> isStaff green
4 07 Replace magic 0.30 with staffPercent green refactor: name discount rates
5 09 Move discount() to CustomerType RED (forgot the coupon rule)
6 10 git restore; smaller step: move only the percent lookup green
7 13 move coupon rule next green refactor: move discount to CustomerTypeFix / how to use it: one named move at a time; run the tests after every move; commit on green; on red, revert instead of debugging a half-refactored state.
Two hats Important
In plain words: at any moment you are either adding behaviour or refactoring, never both. Kent Beck's metaphor, which Fowler uses: you wear one hat at a time.
Common misunderstanding: "I'll fix the bug while I'm in there." Mixing them means a failing test can come from the bug fix or from the restructuring, and the diff reviewers see mixes both.
Definition: (Fowler opens his preparatory-refactoring article with a section called "The Two Hats".) When adding features you add tests and change behaviour; when refactoring you add no behaviour and only change tests whose structure you broke (for example a renamed function). Switch hats often, but know which one you wear. In git this becomes separate commits: refactor: commits that keep every test green, and feat:/fix: commits that change behaviour.
When to refactor: the workflows Must-know
In plain words: refactor when it makes the change in front of you easier, when it helps you understand code you are reading, and whenever you pass by something small and messy.
Common misunderstanding: "Refactoring is a phase." Fowler's Opportunistic Refactoring: "Although there are places for some scheduled refactoring efforts, I prefer to encourage refactoring as an opportunistic activity, done whenever and wherever code needs to cleaned up - by whoever."
Definition: Fowler's Workflows of Refactoring infodeck (2014) names the workflows, and his other writing defines them:
| Workflow | Trigger | Source wording |
|---|---|---|
| TDD refactoring | Just went green | TDD's third step: "Refactor both new and old code to make it well structured." |
| Preparatory refactoring | A feature would be awkward to add | Kent Beck: "make the change easy (warning: this may be hard), then make the easy change" |
| Comprehension refactoring | You struggle to read code | "If I struggle to understand this code, I refactor it so I won't have to struggle again next time I look at it." (refactoring.com) |
| Litter-pickup refactoring | You pass by something messy | The camp-site rule: "always leave the code behind in a better state than you found it." |
| Planned refactoring | The team agrees a known problem needs time | A tracked task; Fowler warns that skipping opportunistic refactoring ends in "difficult conversations with sponsors about refactoring iterations" |
| Long-term refactoring | A large change (replace a library, split a module) | Weeks of small steps, often with Branch by Abstraction |
Every workflow carries the same precondition: "you should only refactor when your tests are green."
Rule of three Important
In plain words: do not abstract on the first or second copy; abstract on the third, when you can finally see what really varies.
Common misunderstanding: "DRY means extract on the second copy." Two copies are often accidental duplication; merging them too early produces the wrong abstraction, which is harder to undo than the duplication.
Definition: refactoring.guru's When to refactor, summarising Fowler: "When you’re doing something for the third time, start refactoring." Wikipedia (secondary) adds Sandi Metz's warning that premature merging "risks selecting a wrong abstraction".
Copy Where What you do
1 1st checkout pricing just write it
2 2nd quote endpoint copy it, wince, leave a TODO with a link to copy 1
3 3rd admin re-price tool now you see what varies (shipping) and what does not (discount)
4 Extract Function + parameter for the varying part; delete the three copiesWhen not to refactor Important
| Situation | Do instead | Why |
|---|---|---|
| No tests and no time to write characterization tests | Write the tests first, or leave it | Without a net you cannot prove behaviour was kept |
| Code that will be deleted next month | Leave it | Paying for structure nobody will use |
| A rewrite is genuinely cheaper (tiny module, wrong technology) | Rewrite behind the same interface | Refactoring assumes the current behaviour is worth keeping |
| Mid-incident or one hour before a release | Note it, come back | Two hats; risk at the worst moment |
| A published API used by other teams | Parallel Change | Renaming it is a contract change, not a refactoring |
The smell catalogue
The five boxes are refactoring.guru's grouping of the 1999 smells (the grouping is the site's, not Fowler's; Fowler's chapter is a flat list). The starred smells are this chapter's 14. The two lower boxes show how Fowler's 2018 list differs: four new smells, four renamed, and three smells that are not in the 2018 list at all.
The family definitions, as refactoring.guru writes them:
| Family | refactoring.guru's definition | Smells |
|---|---|---|
| Bloaters | "code, methods and classes that have increased to such gargantuan proportions that they are hard to work with" | Long Method, Large Class, Primitive Obsession, Long Parameter List, Data Clumps |
| Object-Orientation Abusers | "incomplete or incorrect application of object-oriented programming principles" | Switch Statements, Temporary Field, Refused Bequest, Alternative Classes with Different Interfaces |
| Change Preventers | "if you need to change something in one place in your code, you have to make many changes in other places too" | Divergent Change, Shotgun Surgery, Parallel Inheritance Hierarchies |
| Dispensables | "something pointless and unneeded whose absence would make the code cleaner" | Comments, Duplicate Code, Lazy Class, Data Class, Dead Code, Speculative Generality |
| Couplers | "contribute to excessive coupling between classes or show what happens if coupling is replaced by excessive delegation" | Feature Envy, Inappropriate Intimacy, Message Chains, Middle Man, Incomplete Library Class |
The master table: 1999/refactoring.guru names against Fowler's 2018 list. The 2018 list is the 24 section headings of chapter 3 in the second edition (InformIT excerpt).
| refactoring.guru / 1999 name | Fowler 2018 name | Family | In the 14? |
|---|---|---|---|
| (none) | Mysterious Name | new in 2018 | no |
| Duplicate Code | Duplicated Code | Dispensables | yes (10) |
| Long Method | Long Function | Bloaters | yes (1) |
| Long Parameter List | Long Parameter List | Bloaters | yes (4) |
| (none) | Global Data | new in 2018 | no |
| (none) | Mutable Data | new in 2018 | no |
| Divergent Change | Divergent Change | Change Preventers | yes (8) |
| Shotgun Surgery | Shotgun Surgery | Change Preventers | yes (9) |
| Feature Envy | Feature Envy | Couplers | yes (14) |
| Data Clumps | Data Clumps | Bloaters | yes (5) |
| Primitive Obsession | Primitive Obsession | Bloaters | yes (3) |
| Switch Statements | Repeated Switches | OO Abusers | yes (6) |
| (none) | Loops | new in 2018 | no |
| Lazy Class | Lazy Element | Dispensables | no |
| Speculative Generality | Speculative Generality | Dispensables | yes (13) |
| Temporary Field | Temporary Field | OO Abusers | no |
| Message Chains | Message Chains | Couplers | no |
| Middle Man | Middle Man | Couplers | no |
| Inappropriate Intimacy | Insider Trading | Couplers | no |
| Large Class | Large Class | Bloaters | yes (2) |
| Alternative Classes with Different Interfaces | same | OO Abusers | no |
| Data Class | Data Class | Dispensables | yes (12) |
| Refused Bequest | Refused Bequest | OO Abusers | yes (7) |
| Comments | Comments | Dispensables | yes (11) |
| Parallel Inheritance Hierarchies | not in the 2018 list | Change Preventers | no |
| Incomplete Library Class | not in the 2018 list | Couplers | no |
| Dead Code (refactoring.guru only) | not a smell; Remove Dead Code is a refactoring | Dispensables | no |
The 14 smells, one by one
Each block: plain words, the usual wrong belief, the definition (Fowler's wording where we quote), a Go and a PHP example, the moves, and when it is not a smell. The lab's before code contains most of them in one file.
1. Long Method (Long Function) Must-know
In plain words: one function does several jobs, so you must read all of it to change any of it.
Common misunderstanding: "Long means more than N lines." Fowler: "The key here is not function length but the semantic distance between what the method does and how it does it." A 30-line function that mixes HTTP, SQL and tax rules is long; a 60-line table of cases may not be.
Definition: a function whose body needs comments or blank-line "paragraphs" to be understood. Cure from chapter 3: "Ninety-nine percent of the time, all you have to do to shorten a function is Extract Function". Detect in Go with funlen (default 60 lines / 40 statements), gocognit, gocyclo, nestif; in PHP with PHPMD-style complexity rules or simply review.
// Before: HandleOrder in the lab is ~110 lines: decode, validate, price, ship, reserve, save, respond.
// After: each paragraph became a named function; the handler reads like the comment it replaced.
placed, err := h.Svc.Place(cmd)// Before: 90 lines inside store(). After:
['order' => $order, 'quote' => $quote, 'method' => $method] = $placeOrder->handle($request->toData());Moves: Extract Function; Replace Temp with Query (temps block extraction); Introduce Parameter Object; Decompose Conditional; Split Loop; Replace Function with Command when nothing else works.
When it is not a smell: a linear script (a migration, a main that wires dependencies), a generated parser, or a table-driven test listing cases.
2. Large Class Must-know
In plain words: one type has too many fields and methods, usually because it serves several groups of callers.
Common misunderstanding: "Split it by size." Split it by who uses what: "The clients of such a class are often the best clue for splitting up the class."
Definition: "When a class has too many fields, duplicated code cannot be far behind." The Laravel User model with 60 methods and the Go Server struct with 40 methods are the usual suspects. The anti-pattern at its extreme is the God Object / Blob.
// Smell: one struct for HTTP, pricing, stock and storage.
type Shop struct { prices map[string]float64; stock map[string]int; db *sql.DB; mailer Mailer; tpl *template.Template }
// Cure: Catalog, Pricer, Orders, Handler; each field moved to the type that uses it.// Smell: User has auth, billing, newsletter and GDPR export.
// Cure: BillingProfile and NewsletterPreference models, an ExportUserData action, User keeps relations.Moves: Extract Class (by field prefix: deposit_amount, deposit_currency → Deposit), Extract Superclass, Replace Type Code with Subclasses. See SRP for splitting by actor.
When it is not a smell: a cohesive aggregate that one team changes for one reason, or a facade whose whole job is to be the single entry point.
3. Primitive Obsession Must-know
In plain words: domain ideas (money, email, SKU, status) live in int, float64 and string, so their rules are copied everywhere they are used.
Common misunderstanding: "Small types are overhead." In Go a named type over int64 costs nothing at runtime; a PHP readonly class costs one allocation. The bugs it prevents (float money, mixed-up IDs, typos in status strings) cost far more.
Definition: Fowler and Beck: programmers are "curiously reluctant to create their own fundamental types which are useful for their domain—such as money, coordinates, or ranges", and strings used this way are "stringly typed" variables.
// Before: subtotal += p * float64(it.Qty) // float money, rounding by %.2f at the edge
type Money int64 // cents
func (m Money) Percent(p int64) Money { return m * Money(p) / 100 }final readonly class Money { private function __construct(public int $cents) {} /* plus, minus, percent ... */ }
enum ShippingMethod: string { case Standard = 'standard'; case Express = 'express'; case Pickup = 'pickup'; }Moves: Replace Primitive with Object; Replace Type Code with Subclasses then Replace Conditional with Polymorphism; Extract Class for groups of primitives (that is Data Clumps). In Laravel, custom Eloquent casts map a column to the value object.
When it is not a smell: at the edges (JSON, SQL rows, CLI flags), where the primitive is the wire format; convert at the boundary.
4. Long Parameter List Important
In plain words: a call site you cannot read without the signature open, often with booleans that switch behaviour.
Common misunderstanding: "Use a map or array $options instead." That hides the list without shortening it, and loses types.
Definition: chapter 3 lists the cures in one paragraph: Replace Parameter with Query, Preserve Whole Object, Introduce Parameter Object, and for flags, Remove Flag Argument; and Combine Functions into Class when several functions share the same parameters.
// Before
func price(lines []Line, typ, coupon, shipping, street, city, zip, country string, dryRun bool) (float64, error)
// After: the address is one value, dryRun became two functions (Quote vs Place)
func (p Pricer) Price(lines []Line, t CustomerType, coupon string, ship ShippingMethod, to Address) (Quote, error)// Before: place($email, $type, $items, $street, $city, $zip, $country, $shipping, $coupon, $sendMail = true)
// After: handle(PlaceOrderData $data) with Address and the mail moved to a listenerMoves: Introduce Parameter Object, Preserve Whole Object, Remove Flag Argument, Replace Parameter with Query, Combine Functions into Class.
When it is not a smell: constructors used by a dependency-injection container, where each parameter is one collaborator and the list documents the dependencies.
5. Data Clumps Important
In plain words: the same three or four values keep appearing together: as fields, as parameters, as array keys.
Common misunderstanding: "A struct with public fields is enough." That is a start; the payoff comes when behaviour that uses the clump moves in (Fowler and Beck chose "a class here, not a simple record structure" so feature envy can be cured next).
Definition: the test from chapter 3: "consider deleting one of the data values. If you did this, would the others make any sense? If they don’t, it’s a sure sign that you have an object that’s dying to be born."
type Address struct{ Street, City, Zip, Country string }
func (a Address) Domestic() bool { return a.Country == HomeCountry } // behaviour followed the datafinal readonly class Address { public function isDomestic(): bool { return $this->country === self::HOME_COUNTRY; } }Moves: Extract Class on the fields, then Introduce Parameter Object or Preserve Whole Object on the signatures, then Move Function for envious code.
When it is not a smell: a coordinate passed as (x, y) to a math function, where the pair is the function's natural signature.
6. Switch Statements (Repeated Switches) Must-know
In plain words: the same switch (or if/else chain) on the same type code appears in several places, so adding a case means hunting all of them.
Common misunderstanding: "Every switch should become polymorphism." Fowler changed the smell's name in 2018 precisely to stop that reading: "we now focus on the repeated switch, where the same conditional switching logic ... pops up in different places." One switch in a factory is fine.
Definition: a type code ("standard", "express", "pickup") that drives behaviour in two or more conditionals.
Day Request Before (2 switches) After (interface)
1 D1 add "same-day courier" shipping edit switch in HandleOrder add type courier + one map entry
2 D1 forget the switch for the ETA: eta = "" compiler: courier must implement ETA()
3 D2 support ticket: "ETA is blank" find the second switch, patch (cannot happen)
4 D9 quote endpoint shows wrong price third switch, in HandleQuote, never edited (one Pricer, one copy)type ShippingMethod interface { Cost(net Money, to Address) Money; ETA() string }
var shippingMethods = map[string]ShippingMethod{"standard": standard{}, "express": express{}, "pickup": pickup{}}enum ShippingMethod: string { /* cases */ public function cost(Money $net, Address $to): Money { return match ($this) { /* ... */ }; } }Moves: Replace Conditional with Polymorphism (Go: interface + one type per case; PHP: classes, or a backed enum with methods whose match is exhaustive), Replace Type Code with Subclasses first if the code is a primitive. The OCP page treats the design side.
When it is not a smell: a single switch at the boundary that maps input to a type (the factory), or a match inside one PHP enum, which keeps every case in one file.
7. Refused Bequest Good to know
In plain words: a subtype inherits methods it does not want, and either ignores them or makes them throw.
Common misunderstanding: "Any unused inherited method is a violation." Fowler is relaxed about it: "Nine times out of ten this smell is too faint to be worth cleaning." The strong form is refusing the interface: "We don’t mind refusing implementations—but refusing interface gets us on our high horses." That strong form is an LSP violation.
Definition: a subclass that uses little of what it inherits, or throws BadMethodCallException/returns errors for parent operations.
// Go has no inheritance; the smell shows up with struct embedding:
type ReadOnlyStore struct{ *Store } // embeds Save, Delete ...
func (ReadOnlyStore) Delete(id int) error { return errors.New("not supported") } // refusing the interface
// Cure: do not embed; hold a field and expose only Get (Replace Superclass with Delegate).
type ReadOnlyStore struct{ s *Store }
func (r ReadOnlyStore) Get(id int) (Order, error) { return r.s.Get(id) }class ArchivedOrder extends Order { public function cancel(): void { throw new \LogicException('archived'); } }
// Cure: final class ArchivedOrder { public function __construct(private Order $order) {} /* only reads */ }Moves: Push Down Method / Push Down Field into a sibling (the "traditional" cure), or Replace Subclass with Delegate / Replace Superclass with Delegate (alias Replace Inheritance with Delegation).
When it is not a smell: reusing a bit of behaviour from a base class whose interface the child fully honours.
8. Divergent Change Must-know
In plain words: one module is edited for unrelated reasons: new database today, new tax rule tomorrow.
Common misunderstanding: "It's the same as shotgun surgery." It is the mirror image: divergent change is one module, many reasons; shotgun surgery is one reason, many modules.
Definition: "Divergent change occurs when one module is often changed in different ways for different reasons." This is the SRP violation, seen from the change log.
Week Ticket File edited in the lab's before code
1 W1 new carrier rate (logistics) before/handler.go
2 W2 VIP 12% (marketing) before/handler.go
3 W3 move orders to PostgreSQL before/handler.go
4 W4 new JSON field (mobile team) before/handler.go -> four teams, one file, four merge conflicts// Cure: Split Phase (decode -> PlaceOrder command -> Service.Place -> Placed -> encode) and one type per reason:
// shipping.go (logistics), customer.go (marketing), catalog.go/order.go (storage), http.go (API).// Cure: PlaceOrderRequest (API), CustomerType (marketing), ShippingMethod (logistics), PlaceOrder (use case).Moves: Split Phase when the reasons form a sequence; Extract Function then Move Function; Extract Class.
When it is not a smell: early in a project, when boundaries are still unknown; Fowler notes you "often discover this only after you’ve added a few databases or financial instruments".
9. Shotgun Surgery Must-know
In plain words: one small change forces many small edits in many files, and the one you forget is the bug.
Common misunderstanding: "More, smaller classes are always better." Over-splitting causes shotgun surgery. Fowler even recommends temporarily going the other way: inline the scattered pieces into one place, "we aren’t afraid of creating something large as an intermediate step to reorganization", then extract sensible pieces.
Definition: "every time you make a change, you have to make a lot of little edits to a lot of different classes."
Step "Free shipping from 50 becomes 60" Files to edit before After
1 handler (HandleOrder) before/handler.go:114 shipping.go: freeShippingFrom
2 handler (HandleQuote) before/handler.go:190 (same constant)
3 checkout banner text resources/views/cart.blade.php reads the constant via a view composer
4 email template one more copy, missed (gone)const freeShippingFrom = Money(5000) // one placeprivate const FREE_FROM_CENTS = 5000; // inside ShippingMethod, the only ownerMoves: Move Function and Move Field into one module; Combine Functions into Class / into Transform; Inline Function / Inline Class first if the logic is scattered.
When it is not a smell: a cross-cutting change that is meant to touch everything (renaming a field across an API), done with a tool in one commit.
10. Duplicate Code (Duplicated Code) Must-know
In plain words: the same logic in two places; every fix must be made twice, and one copy is always forgotten.
Common misunderstanding: "Anything that looks the same is duplicate." Code that looks the same but belongs to different owners and changes for different reasons is accidental duplication; see SRP and the rule of three.
Definition: "If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them." Cures in chapter 3: Extract Function; Slide Statements to line up near-duplicates first; Pull Up Method when the copies are in sibling subclasses.
Day Event in the lab's before code
1 D1 HandleQuote created by copying the pricing half of HandleOrder
2 D20 HandleOrder gains qty and stock validation; HandleQuote does not
3 D35 unknown shipping: HandleOrder returns 422, HandleQuote silently charges 0
4 D36 the characterization test pins both behaviours; unifying them is a product decision, not a refactoring// After: both endpoints call the same Pricer.Price; the quote keeps its old quirk explicitly (see the lab).
q, err := s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)// After: PriceQuote::calculate() is the only copy of the pricing rules.Moves: Extract Function, Slide Statements, Pull Up Method, Form Template Method (1st edition name), Substitute Algorithm. Detect with dupl (golangci-lint, default threshold 150 tokens) and PHPStorm's duplicate detection.
When it is not a smell: two copies owned by different actors (keep them), or test fixtures where repetition makes each test readable on its own.
11. Comments Important
In plain words: a comment that explains what a block does is a function name waiting to be written.
Common misunderstanding: "Fowler says comments are bad." He says the opposite: "comments aren’t a bad smell; indeed they are a sweet smell." The smell is that "comments are often used as a deodorant."
Definition: "When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous." Comments that explain why, or mark uncertainty, stay: "A comment can also explain why you did something."
// Before: // discount: vip 10%, staff 30%, coupon 5 off except for staff
// After: the comment became the code.
func (t CustomerType) Discount(subtotal Money, coupon string) Money// Before: // the same switch again
// After: ShippingMethod::eta(); the remaining comment explains WHY unknown shipping costs 0 in quotes.Moves: Extract Function (name it after the comment), Change Function Declaration (rename), Introduce Assertion for "this must be true here" comments.
When it is not a smell: package and exported-API documentation (Go's ST1020-style doc comments), legal headers, "why" comments, links to tickets or RFCs.
12. Data Class Important
In plain words: a type with fields and getters/setters while all the logic about it lives in other classes.
Common misunderstanding: "Every struct must have behaviour." Fowler's exception: "one of the best exceptions is a record that’s being used as a result record from a distinct function invocation", such as the result of Split Phase; and immutable records need no encapsulation. DTOs at the edge and Laravel API Resources are fine. The domain-model version of this smell is the anemic domain model.
Definition: "classes that have fields, getting and setting methods for the fields, and nothing else ... often being manipulated in far too much detail by other classes."
// Fine: Quote is a result record of Pricer.Price, immutable in practice.
type Quote struct{ Subtotal, Discount, Shipping, Total Money }
// Smell: an Order struct whose total, status rules and refunds are computed in five handlers.// Smell: an Eloquent model with only $fillable while controllers compute status transitions.
// Cure: $order->cancel(), $order->refund(Money $amount) on the model or a domain object.Moves: Encapsulate Record, Remove Setting Method, Move Function into the data class, Extract Function first if only part can move.
When it is not a smell: DTOs, API request/response shapes, event payloads, read models, and Split Phase result records.
13. Speculative Generality Important
In plain words: abstractions, parameters and hooks added for a future that never arrived.
Common misunderstanding: "An interface for everything makes code testable." In Go, interfaces belong to the consumer and are introduced when a second implementation or a test needs one; a Repository interface with one implementation and no fake is speculation.
Definition: a name Brian Foote suggested; the tell in chapter 3: "Speculative generality can be spotted when the only users of a function or class are test cases."
// Smell: type PricerFactory interface{ New(opts ...PricerOption) Pricer } with one implementation and no option ever passed.
// Cure: delete the factory; call the constructor. Detect unused params with unparam, unused code with unused.// Smell: AbstractShippingCalculatorFactoryInterface with one implementation and a $strategy = null nobody passes.
// Cure: Rector's deadCode set removes unused private methods and params; Collapse Hierarchy for the rest.Moves: Collapse Hierarchy, Inline Function, Inline Class, Change Function Declaration (remove unused parameters), Remove Dead Code.
When it is not a smell: a published library or plugin API where extension points are the product; a seam you need now for a test.
14. Feature Envy Must-know
In plain words: a function that reads more of another type's data than of its own; it wants to live there.
Common misunderstanding: "Move every function to the data it touches." Strategy and Visitor deliberately keep behaviour apart from data; Fowler names them as the legitimate exceptions. The rule underneath is "put things together that change together."
Definition: "a function in one module spends more time communicating with functions or data inside another module than it does within its own module." Heuristic for functions that use several modules: move it to the one with most of the data.
// Before (in the handler): if req.Country == "NL" { shipping = 4.95 } ...
// After: the address answers the question itself.
func (a Address) Domestic() bool { return a.Country == HomeCountry }// Before: $data['country'] == 'NL' ? 4.95 : 9.95 in the controller. After: $to->isDomestic() on Address.Moves: Move Function; Extract Function on the envious part, then Move Function.
When it is not a smell: Strategy, Visitor and other patterns that separate behaviour from data on purpose; read-only projections (a report builder reading many models).
The other smells
The rest of the catalogue in one table each: definition, a Go hint, a PHP hint, the moves, and when it is fine.
| Smell | Definition | Go example | PHP example | Moves | Not a smell when |
|---|---|---|---|---|---|
| Temporary Field | A field set only in some circumstances | retryAt time.Time used only by one code path | ?Carbon $retryAt null most of the time | Extract Class, Move Function, Introduce Special Case | Lazy caches documented as such |
| Alternative Classes with Different Interfaces | Two types do the same job with different method names | SMTPMailer.Send vs SESMailer.Deliver | StripeGateway::charge vs MollieGateway::pay | Change Function Declaration, Move Function, Extract Superclass / interface | Third-party types you wrap with an adapter anyway |
| Parallel Inheritance Hierarchies | Every new subclass in one hierarchy forces one in another | XMLExporter + XMLValidator for each format (via interfaces) | PdfInvoice + PdfInvoiceRenderer pairs | Move Function, Move Field until one hierarchy disappears | The pairs belong to different layers on purpose (domain vs adapter) |
| Lazy Class (Lazy Element) | A class or function that no longer earns its keep; "such program elements need to die with dignity" | A package with one 3-line function | A Helper class with one static method | Inline Function, Inline Class, Collapse Hierarchy | A named seam you are about to grow |
| Dead Code | Code never executed (refactoring.guru; Fowler treats it as the refactoring Remove Dead Code) | Unexported func nobody calls (unused) | Unused private method (PHPStan level 4 dead branches, Rector deadCode) | Remove Dead Code; trust version control | Feature-flagged code with an owner and a removal date |
| Inappropriate Intimacy (Insider Trading) | Modules that know each other's internals; "Modules that whisper to each other by the coffee machine" | Package billing reading orders' unexported fields via a shared internal helper | Model reaching into another module's tables with DB::table('other_module_x') | Move Function, Move Field, Hide Delegate, Replace Subclass/Superclass with Delegate | Two types inside one cohesive package |
| Message Chains | a.B().C().D(); "the client is coupled to the structure of the navigation" | order.Customer().Account().Plan().Limit() | $order->customer->account->plan->limit | Hide Delegate, Extract Function + Move Function down the chain | Fluent builders and query builders (User::query()->where()->get()) |
| Middle Man | "half the methods are delegating to this other class" | A Service whose methods only call the repository | A Laravel service class that forwards to Eloquent one-to-one | Remove Middle Man, Inline Function, Replace Superclass/Subclass with Delegate | Proxy, Decorator, Facade, anti-corruption layers |
| Incomplete Library Class | A library lacks a method you need and you cannot change it | Missing helper on a third-party client | Missing method on a vendor class | Introduce Foreign Method / Local Extension (1st ed.); in Go a wrapper type, in PHP a wrapper or macro (Collection::macro) | Contribute upstream when you can |
| Mysterious Name (2018) | Names that hide intent; "When you can’t think of a good name for something, it’s often a sign of a deeper design malaise." | func proc(d map[string]any) | function handle2($x) | Change Function Declaration, Rename Variable, Rename Field | Short names in tiny scopes (i, err, r) |
| Global Data (2018) | Data "modified from anywhere in the code base" | var Prices = map[string]float64{...} in the lab | config() written at runtime, static properties | Encapsulate Variable, then narrow the scope | Constants and read-only config fixed at start-up |
| Mutable Data (2018) | Updates in one place surprise code elsewhere | Returning an internal slice callers can append to | Mutating a shared array by reference | Encapsulate Variable, Split Variable, Separate Query from Modifier, Remove Setting Method, Change Reference to Value | Local variables in a short scope |
| Loops (2018) | A loop whose intent hides behind index juggling | Manual filter + sum loops (Go has no pipelines; a named helper or slices functions) | foreach that builds an array → collect()->filter()->sum() | Replace Loop with Pipeline | Go hot paths; a plain loop is idiomatic Go |
Refactoring moves catalogue
The full catalogue on refactoring.com has about 60 cards; these are the ones every team uses weekly. Each card on the site shows the 2nd-edition name, aliases and the inverse.
| Move | Alias / inverse | Mechanics in one line | Go | Laravel / PHP | IDE |
|---|---|---|---|---|---|
| Extract Function | alias Extract Method; inverse Inline Function | Name the fragment, pass what it reads, return what it writes | New unexported func or method | Private method, or an invokable Action | gopls refactor.extract.function / .method; PhpStorm Extract Method |
| Inline Function | alias Inline Method | Replace calls with the body, delete the function | gopls refactor.inline.call | PhpStorm Inline | both |
| Extract Variable | alias Introduce Explaining Variable; inverse Inline Variable | Name a sub-expression | isStaff := t == Staff | $isStaff = ... | gopls refactor.extract.variable; PhpStorm Extract Variable |
| Change Function Declaration / Rename | Rename Function, Add/Remove Parameter, Change Signature | Rename or reshape, update all callers (migrate in steps if published) | gopls rename; gopls removeUnusedParam | PhpStorm Rename, Change Signature | both |
| Move Function / Move Field | alias Move Method | Copy to the target, delegate from the old place, then inline the delegate | Move to the package owning the data | Move from controller to model/value object | PhpStorm Move |
| Replace Temp with Query | Turn a temp into a function so extraction needs fewer parameters | func (q Quote) net() Money | private function net(): Money | manual | |
| Introduce Parameter Object | Group parameters into a type, pass it | PlaceOrder struct | PlaceOrderData readonly class | manual (PhpStorm Extract Class helps) | |
| Replace Conditional with Polymorphism | One type per case; the switch becomes a call | Interface + types | Classes, or enum methods | manual | |
| Replace Type Code with Subclasses | aliases Extract Subclass, Replace Type Code with State/Strategy | Make the code a type first | Named type + interface | Backed enum, then classes if behaviour grows | manual |
| Decompose Conditional | Extract the condition and each branch into named functions | acceptsCoupon() | acceptsCoupon() | Extract Method | |
| Extract Class | inverse Inline Class | New type, move fields, then methods, one at a time | New type or package | Value object, model, Action | PhpStorm Extract Delegate |
| Pull Up Method / Push Down Method | inverses of each other | Move a method to the parent / to the subclasses that use it | Not applicable (no inheritance); move into an embedded helper or out of it | PhpStorm Pull Members Up / Push Members Down | PhpStorm |
| Replace Superclass with Delegate | alias Replace Inheritance with Delegation | Hold the former parent as a field, forward only what you need | Field instead of embedding | private Order $order instead of extends Order | manual |
| Introduce Special Case | alias Introduce Null Object | One object for the special value with the default behaviour | pickup{} used for unknown quotes | GuestCustomer with name() => 'occupant' | manual |
| Separate Query from Modifier | One function answers, another changes state | Pricer.Price vs Catalog.Reserve | PriceQuote::calculate vs PlaceOrder::handle | manual | |
| Encapsulate Collection | Return copies or read-only views; add/remove through methods | All() returns a copy | Return a Collection copy, never the internal array by reference | manual | |
| Split Phase | Put a data structure between two phases | decode → PlaceOrder → Place | Form Request → DTO → Action → Resource | manual | |
| Hide Delegate / Remove Middle Man | inverses of each other | Add a forwarding method / remove too many of them | order.CustomerPlan() | $order->customerPlan() | manual |
| Replace Magic Literal | alias Replace Magic Number with Symbolic Constant | Name the literal | const freeShippingFrom = Money(5000) | private const FREE_FROM_CENTS = 5000 | PhpStorm Extract Constant; gopls refactor.extract.constant |
| Remove Dead Code | Delete it; version control remembers | unused finds it | PHPStan / Rector deadCode | both |
Mechanics of the big four, in Go and PHP
Replace Conditional with Polymorphism. (1) Make sure the type code is a type (ShippingMethod), not a string. (2) Create one implementation per case with the same method returning the case's value. (3) Replace one case at a time with a call; tests after each. (4) When the switch only dispatches, replace it with the call; keep one factory map/tryFrom at the boundary. The lab's shipping.go and ShippingMethod.php are the result.
Replace Inheritance with Delegation (Replace Superclass with Delegate). (1) Add a field holding an instance of the former parent. (2) For each parent method the child really uses, add a forwarding method. (3) Remove extends (PHP) or the embedding (Go). (4) Delete forwards nobody calls.
// Before: embedding exports every Store method, including ones a read-only view must refuse.
type Report struct{ *Store }
// After: delegate only what the report needs.
type Report struct{ store *Store }
func (r Report) Orders() []Order { return r.store.All() }Introduce Special Case (Null Object). (1) Find repeated checks for a special value (if customer == nil, $customer === null). (2) Create a type for it with the default behaviour. (3) Return it from the lookup instead of nil/null. (4) Delete the checks one by one.
final class GuestCustomer implements Customer
{
public function name(): string { return 'occupant'; }
public function discountPercent(): int { return 0; }
}
// $customer = $repo->find($id) ?? new GuestCustomer(); // the null checks disappearSeparate Query from Modifier. A function that returns a value and changes state cannot be called "just to look". Split it: the query is safe to call twice, in a quote endpoint, a test, or a retry; the modifier does one thing. Fowler's card: getTotalOutstandingAndSendBill() becomes totalOutstanding() and sendBill(). In the lab, Pricer.Price is the query and Catalog.Reserve is the modifier, which is what made one pricing copy possible.
Anti-patterns
In plain words: an anti-pattern is a solution that looks reasonable, gets repeated, and produces more problems than it solves. A smell is a symptom in the code; an anti-pattern is a recurring design decision that produces many smells.
Common misunderstanding: "An anti-pattern is just bad code." Brown et al. require two parts: the recurring bad solution and a refactored solution. The authors' site calls a description without the way out "a pseudo-AntiPattern, closer to a complaint than a diagnosis."
| Anti-pattern | Source and wording | Smells it produces | Refactored solution | Go / Laravel example |
|---|---|---|---|---|
| God Object / The Blob Must-know | AntiPatterns (1998): "One class or object monopolizes behavior. Alias: God Class." | Large Class, Divergent Change, Feature Envy elsewhere | Distribute responsibility: Extract Class by actor | Server with 40 methods; User model with 3,000 lines |
| Spaghetti Code | AntiPatterns: "Control flow with no discernible structure." | Long Function, nested conditionals | Extract Function, guard clauses, modules with meaningful names | goto-like flag variables; 8-level nested if in a controller |
| Cut-and-Paste Programming | AntiPatterns: "Reuse by duplication." | Duplicated Code, Shotgun Surgery | One abstraction, after the rule of three | Copied handlers in the lab |
| Golden Hammer | AntiPatterns: "A familiar tool applied to every problem." | Speculative Generality, wrong abstractions | Choose the tool after the problem | Kafka for a 10-msg/min job queue; Redis as the primary database for relational data |
| Lava Flow | AntiPatterns: "The Lava Flow of obsolete technologies and forgotten extensions leaves hardened globules of dead code in its wake." | Dead Code, Speculative Generality | System discovery: find what is used, delete the rest, with tests | legacy_v2/ package nobody dares to delete |
| Poltergeists | AntiPatterns: "Short-lived objects that exist only to pass messages." | Middle Man, Lazy Class | Collapse the ghost: Inline Class | OrderManagerStarter that only calls OrderManager |
| Boat Anchor | AntiPatterns: "A costly component kept because it was costly." | Dead Code, Speculative Generality | Remove it | An unused rules engine still wired into the container |
| Magic Numbers | Wikipedia's Anti-pattern article (secondary): "A literal value with an important yet unexplained meaning" | Primitive Obsession, Shotgun Surgery | Replace Magic Literal | 4.95, 0.30, 50 in the lab's before code; mnd linter |
| Cargo Cult Programming | Wikipedia (secondary): ritual inclusion of code or structure that serves no real purpose | Speculative Generality, Middle Man | Ask what each layer does; delete what does nothing | A repository interface + service + DTO for a one-line CRUD endpoint "because Clean Architecture" |
| Functional Decomposition | AntiPatterns: "Procedural design wearing object clothing." | Data Class, Feature Envy | Objects that own data and behaviour | Eloquent models as bags of columns, logic in *Service classes |
Real scenarios: the payments Helper.php that every feature imports (Blob); a microservice built for each of the team's favourite tools (Golden Hammer); a v1/ directory that is "probably unused" (Lava Flow); a Laravel app where every class has an interface with exactly one implementation (Cargo Cult).
Architectural smells
In plain words: the same idea one level up: signs in the dependency graph between packages, modules or services that change will be expensive.
Common misunderstanding: "Architecture smells need special tools." The first three are visible in go list -deps, composer autoload graphs or an import diagram; the last two are visible in your database grants and deploy logs.
Definition: Sas, Avgeriou and Uyumaz (2022), reporting the definitions of Arcelli Fontana et al. (2017) as implemented in the Arcan tool:
| Smell | Definition (paraphrase unless quoted) | Go | Laravel / PHP | Cure |
|---|---|---|---|---|
| Cyclic Dependency Must-know | "a cycle among a number of components" | The compiler forbids import cycles between packages ("import cycle not allowed") | Allowed by PHP; modules A and B call each other's classes | Extract the shared concept into a third module; invert one edge with an interface (DIP) |
| Hub-Like Dependency | A component whose incoming and outgoing dependencies are both above the system median and roughly balanced | A common or models package everyone imports and that imports everyone | App\Services\Helper | Split the hub by purpose; Move Function to callers |
| Unstable Dependency | "a component that depends upon a significant number of components that are less stable than itself" (Arcan uses a 30% threshold, Martin's instability metric) | A stable domain package importing an often-changed httpapi package | Domain model importing a controller helper | Depend in the direction of stability; move the volatile piece behind an interface |
| God Component | A component that is too large (the package-level Blob) | internal/app with 200 files | app/Models folder edited by every team | Split into modules by business capability |
| Shared Database (between services) | microservices.io lists the drawbacks: "Development time coupling" and "Runtime coupling" | Two Go services writing orders | Two Laravel apps on one MySQL schema | One owner per table; publish events or an API; see Data Ownership |
| Distributed Monolith | Practitioners' term (no primary definition quoted here): services that must change and deploy together | Four services, one release train | Shared models Composer package across services | Re-draw boundaries by business capability; see Service Boundaries |
The SQL below is how the shared-database smell looks in grants, and the refactored version where each service owns its schema:
-- Smell: both services connect as the same role and write the same tables.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app; -- orders-svc and billing-svc both use "app"
-- Refactored: one schema and one writer per service; others read through an API or events.
CREATE SCHEMA orders; CREATE SCHEMA billing;
CREATE ROLE orders_svc LOGIN; CREATE ROLE billing_svc LOGIN;
GRANT USAGE, CREATE ON SCHEMA orders TO orders_svc;
GRANT USAGE, CREATE ON SCHEMA billing TO billing_svc;
REVOKE ALL ON SCHEMA orders FROM billing_svc; -- billing learns about orders from OrderPlaced eventsMechanics
The refactoring loop Must-know
On the left is TDD's cycle, which Fowler summarises as "Red - Green - Refactor" and warns about: "The most common way that I hear to screw up TDD is neglecting the third step." On the right is what happens inside the refactor step: spot a smell, pick one named move, take a step small enough to finish in minutes, run the tests, commit on green, revert on red. Behaviour never changes inside the right-hand loop.
The safety net: tests you can trust Must-know
| Net | What it is | Use when | Go | Laravel |
|---|---|---|---|---|
| Unit tests | Fast tests of one function or type | The code already has them | go test ./... | Pest / PHPUnit unit tests |
| Characterization test (golden master) | Records what the code does now, quirks included | Legacy code with no tests | httptest replay with exact bodies (the lab's labtest) | Feature tests with assertExactJson |
| Approval / snapshot test | Stores output in a file and diffs it | Large outputs (reports, PDFs, JSON) | Golden files under testdata/ with an -update flag | Snapshot assertions package, or a stored fixture |
| Type checker and static analysis | Catches broken references during moves | Every step | Compiler, go vet, staticcheck | PHPStan at the highest level you can hold |
| Mutation testing | Changes the code and checks a test fails | You doubt the tests' strength | Third-party mutation tools | Infection |
A characterization test is written against the old code, must pass on it, and must keep passing on every step. If it fails, either your step changed behaviour (revert) or you found a behaviour you want to change (stop, finish the refactoring, then change it in a separate commit with a new test).
Step Action labtest result
1 write labtest against before/ PASS (14 cases)
2 point labtest at after/ (first version) FAIL: body has trailing "\n" (json.Encoder)
3 switch to json.Marshal + w.Write PASS
4 add a negative-qty quote case FAIL on after/: Money prints "-7.-55"
5 fix Money.String for negative amounts PASSCommit and review discipline Important
| Rule | Why |
|---|---|
| One refactoring move (or a few trivial ones) per commit | Bisect and revert stay meaningful |
Prefix: refactor: commits never change tests' expectations | Reviewers can skim them; the tests prove safety |
| Behaviour changes in their own commits, after the refactoring | Two hats in git history |
| Rename in one commit, with the tool, nothing else | Huge diffs that are trivially correct |
| Push refactorings early, as separate PRs | Reviewers see small diffs; features land on clean code |
Large changes: parallel change and branch by abstraction Important
Parallel Change (expand and contract). Danilo Sato on Fowler's bliki: "Parallel change, also known as expand and contract, is a pattern to implement backward-incompatible changes to an interface in a safe manner, by breaking the change into three distinct phases: expand, migrate, and contract." Use it when callers are outside your control (published APIs, other teams, the database schema).
Release Expand / migrate / contract: rename orders.total (float) to orders.total_cents (bigint)
1 R1 expand: add total_cents; write both columns; read total
2 R2 backfill total_cents for old rows; read total_cents, fall back to total
3 R3 migrate readers (reports, other services) to total_cents
4 R4 contract: stop writing total; drop it in a later releaseBranch by Abstraction. Fowler's bliki describes a technique "for making a large-scale change to a software system in gradual way that allows you to release the system regularly while the change is still in-progress." Introduce an interface in front of the thing being replaced, move callers to it, build the new implementation behind it, switch, delete the old one. It is how you replace a payment library or an ORM without a long-lived branch.
Tooling
Tools find smells and perform mechanical moves; they never decide which move is right.
Go Must-know
| Tool | What it does for refactoring | Example |
|---|---|---|
gofmt -r | Syntactic rewrite rules of the form "pattern -> replacement" (single lowercase letters are wildcards) | gofmt -r 'a.Total() -> a.Sum()' -w . |
| gopls code actions | refactor.extract.function, .method, .variable, .constant, .toNewFile; refactor.inline.call, .variable; refactor.rewrite.removeUnusedParam, moveParamLeft/Right | In any LSP editor; gopls's docs note Extract and Inline "are prone to losing comments" |
gopls rename | Type-aware rename across the module, including renaming a package | gopls rename -w before/handler.go:#1450 placeOrder |
go vet | Suspicious constructs | Runs on every lab step |
| staticcheck | Simplifications (S1xxx), style (ST1xxx, e.g. ST1003 poorly chosen identifier, ST1013 magic HTTP codes), dead code like SA4006 value never read | staticcheck ./... |
| golangci-lint | Runs many linters; the smell detectors are below | golangci-lint run |
| golangci-lint linter | Smell it flags |
|---|---|
funlen (defaults 60 lines, 40 statements) | Long Function |
gocognit, gocyclo, cyclop, nestif, maintidx | Long Function, complex conditionals |
dupl (default 150 tokens) | Duplicated Code |
goconst, mnd | Magic numbers and repeated strings |
unused, unparam | Dead Code, Speculative Generality |
gochecknoglobals | Global Data |
interfacebloat | Large Class at the interface level |
depguard | Architectural rules: forbid imports between layers |
# .golangci.yml (golangci-lint v2 format)
version: "2"
linters:
enable: [funlen, gocognit, dupl, goconst, mnd, unparam, gochecknoglobals, nestif]
settings:
funlen:
lines: 60
statements: 40
gocognit:
min-complexity: 15
dupl:
threshold: 100PHP and Laravel Must-know
| Tool | Role | Detail |
|---|---|---|
| PHPStan | Static analysis, the safety net for moves in PHP | "you can currently choose from 11 levels (0 is the loosest and 10 is the strictest)"; "Levels are cumulative"; a baseline file lets you raise the level without fixing old errors first; Larastan adds Laravel knowledge |
| Rector | Automated refactoring rules, run in CI or locally with --dry-run | withPreparedSets(deadCode: true, codeQuality: true, codingStyle: true, typeDeclarations: true, ...); levels raised one at a time (withDeadCodeLevel, withCodeQualityLevel, withTypeCoverageLevel) |
| Laravel Pint | Code style only; "an opinionated PHP code style fixer for minimalists", built on PHP CS Fixer | Not a refactoring tool: it never changes structure; run it so refactoring diffs are not polluted by whitespace |
| PhpStorm | Interactive refactorings with preview and conflict dialog | Rename, Change Signature, Extract Method / Variable / Constant / Class / Interface / Superclass, Extract Delegate, Encapsulate Fields, Inline, Move, Pull Members Up / Push Members Down |
| PHPStan level | Adds (cumulative) |
|---|---|
| 0 | Unknown classes, functions, methods on $this, wrong argument counts, always-undefined variables |
| 1–3 | Possibly undefined variables, magic members, PHPDoc validation, return types, property types |
| 4 | Basic dead code: always-false instanceof, dead else branches, unreachable code after return |
| 5–6 | Argument types; missing typehints |
| 7–8 | Partially wrong union types; nullable access |
| 9–10 | Strict mixed; level 10 (PHPStan 2.0) also implicit mixed |
<?php // rector.php: start small, one level per pull request
use Rector\Config\RectorConfig;
return RectorConfig::configure()
->withPaths([__DIR__.'/app', __DIR__.'/tests'])
->withPreparedSets(deadCode: true, codeQuality: true)
->withTypeCoverageLevel(0);Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Fat controller / fat handler | Split Phase into Laravel's or Go's slots | Form Request / decode → DTO → Action / Service → Resource / encode | Each phase tested alone | More files |
| Money as float | Replace Primitive with Object | Money in cents, conversion at the edge | Exact arithmetic, one formatter | Wire-format and sign care (the lab's negative quote) |
| The same switch in six files | Replace Conditional with Polymorphism | Interface or enum with methods; one factory | New case = one new type | Indirection for two-case switches is not worth it |
| Copy-pasted endpoint | Extract Function after the rule of three; Separate Query from Modifier | One pricing function used by both | One fix fixes both | Divergences surface and need a product decision |
| Global maps / singletons | Encapsulate Variable, then inject | Type owns the data; constructor injection | Tests can create fresh state | Wiring code in main / providers |
| God model | Extract Class by actor | Value objects, related models, Actions, Policies | Fewer merge conflicts | Schema migrations for moved columns |
| Legacy code with no tests | Characterization tests first | Replay real requests, pin outputs | Safe refactoring | Pinned quirks must be fixed later, on purpose |
| Published interface needs a new shape | Parallel Change | Expand, migrate callers, contract | No big-bang release | Two code paths for a while |
Fat controller and fat handler
The lab is this problem end to end. Measured on the snippets: the Go handler file went from one 207-line file with 2 handler functions to 9 small files where http.go holds only decoding, one call and encoding; the Laravel controller's store() went from about 90 lines with 6 use imports to 8 lines.
The switch in six files
# find every switch on the same type code before replacing it (Go and PHP)
grep -rn --include='*.go' 'case "express"' . ; grep -rn --include='*.php' "'express'" app/Then apply Replace Conditional with Polymorphism, one case per commit.
Choosing: refactor, rewrite or leave it
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Feature is awkward to add | Preparatory refactoring, then the feature | Separate commits | Make the change easy first |
| Code you are reading is confusing | Comprehension refactoring (rename, extract) | Throw away if you only needed to understand | Understanding is the product |
| Small mess on your path | Litter-pickup | Timebox to minutes | Camp-site rule |
| Same logic appears a third time | Extract | Parameterize what varies | Rule of three |
| Legacy module, no tests, must change | Characterization tests, then refactor | Golden master | Without a net, no refactoring |
| Big structural problem (wrong library, God Component) | Planned, long-term refactoring | Branch by Abstraction, Parallel Change | Release throughout |
| Module is small and its behaviour is wrong anyway | Rewrite behind the same interface | Contract tests | Preserving wrong behaviour is waste |
| Code is stable and nobody needs to change it | Leave it | Note the smell | Refactoring pays back only on change |
| Splitting a monolith | Refactor to modules inside the monolith first, then extract | Strangler Fig | Cheap moves before network boundaries |
In architecture: from a single process to a distributed system
Refactoring is defined by preserved observable behaviour. That is easy to check inside one process and gets harder as soon as callers sit on the other side of a network.
Monolith: one process, one database
How it shows up: all classic smells, all moves available, the compiler (Go) or PHPStan (PHP) and the test suite check every step, and a rename is one commit.
Simplest correct usage: refactor continuously, keep refactor: commits separate, run the full suite on each.
Example (simple): a blog's PostController@store grows tag parsing; extract a TagParser, add a unit test, done in one PR.
Example (complex): the lab: an order handler with every smell becomes nine cohesive files, guarded by a characterization test.
Modular monolith and multiple databases
How it shows up: smells move up a level: cyclic dependencies between modules, a hub-like Shared module, one module reading another's tables. Refactoring moves become Move Function across a module boundary, which also changes the module's public API.
Rules: each module has a facade; moves inside a module are free; moves across modules go through the facade and may need Parallel Change. Enforce with Go's internal/ and the compiler's import-cycle check, and with depguard; in PHP with architecture tests (Pest arch() or deptrac rules).
Example: Billing reads orders.total directly (Insider Trading). Refactor: add Orders\Api::totalFor(int $orderId): Money, move Billing to it, revoke Billing's grant on the orders table.
Microservices: refactoring across a network
What survives: inside one service, everything above. What breaks: a change to a service's API or event schema is not a refactoring in Fowler's sense, because the observable behaviour is the contract other teams use. It is a contract change, done with versioning or expand/contract.
Extracting a service from the monolith is where refactoring and architecture meet. Do the cheap moves first, in-process, where they are reversible:
Step Where Move Behaviour
1 monolith characterization tests around the shipping logic same
2 monolith Extract Class -> ShippingMethod; Move Function out of controllers same
3 monolith Introduce an interface (Branch by Abstraction) at the seam same
4 monolith remove shared tables: shipping owns its rates table (Parallel Change) same
5 network new shipping-svc implements the interface over HTTP/gRPC same, slower
6 router / gateway Strangler Fig: route a percentage of calls to shipping-svc, compare same
7 monolith delete the in-process implementation sameSteps 1–4 are refactoring; step 5 onwards is migration, covered on Strangler Fig. Fowler's Strangler Fig article: "the term “Strangler Fig” is now often used to describe a gradual approach to legacy modernization."
Distributed data: replicas, caches and shared schemas
Where refactoring breaks: data outlives code. Renaming a column, splitting a table or changing a cached value's shape is visible to every reader, including replicas, analytics jobs, other services and cache entries written by the old version. Each needs expand/contract: write both shapes, migrate readers, then drop the old one. A cache key's value format is a schema too: version the key (order:v2:42) instead of changing the value in place.
Smells at this level: shared database between services, a reporting replica queried by every team (hub-like), events whose payload is the internal table row (Insider Trading over the network).
Scaling path: 1×, 10×, 100×
| Scale | Structure | Refactoring practice |
|---|---|---|
| 1× (one team, one app) | Monolith | Opportunistic refactoring, linters in CI, characterization tests for legacy parts |
| 10× (several teams, one repo) | Modular monolith | Module facades, import rules (depguard, deptrac), dependency-graph review each quarter for cycles and hubs |
| 100× (many teams, many services) | Services by business capability | Refactor inside services freely; change contracts with versioning and expand/contract; Strangler Fig for extractions |
Lab: refactor a smelly Go handler and a smelly Laravel controller
You start from code that works and has every smell on this page, write a characterization test against it, and refactor in small steps until it looks like the "after" code, with the test green after every step.
The left side is the starting point: two handlers sharing global maps, one a copy of the other. The right side is the end state: a thin HTTP adapter, one Service, a Catalog that owns the stock, a Pricer that is the single copy of the pricing rules, and ShippingMethod implementations instead of two switches. Arrows point at dependencies; the leaves (Money, Address, CustomerType) change least.
Part A: Go
Setup.
cd docs/snippets/design/code-smells-refactoring/go
go vet ./... && go test ./...
# ok academy/code-smells-refactoring/after
# ok academy/code-smells-refactoring/beforeThe starting point. Read it and list the smells before you look at the answer: you should find at least long function, primitive obsession (float64 money, string type codes), data clumps (address), repeated switches, duplicated code (HandleQuote), global data, magic numbers, comments as deodorant and feature envy.
// Package before is the smelly starting point of the lab: two HTTP handlers
// that validate, price, ship, reserve stock and save, all inline.
// It works. Every smell on the page is in here somewhere.
package before
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
)
// Global mutable data: anyone can change prices, stock or orders.
var (
Prices = map[string]float64{"BOOK": 12.50, "MUG": 8.00, "LAMP": 40.00}
Stock = map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1}
Orders = []map[string]any{}
mu sync.Mutex
)
// Reset puts the global state back; only tests call it.
func Reset() {
mu.Lock()
defer mu.Unlock()
Stock = map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1}
Orders = []map[string]any{}
}
type item struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
// Data clump: street, city, zip and country always travel together.
type orderRequest struct {
Email string `json:"email"`
Type string `json:"customer_type"` // "regular", "vip", "staff"
Items []item `json:"items"`
Street string `json:"street"`
City string `json:"city"`
Zip string `json:"zip"`
Country string `json:"country"`
Shipping string `json:"shipping"` // "standard", "express", "pickup"
Coupon string `json:"coupon"`
}
func writeErr(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
fmt.Fprintf(w, `{"error":%q}`, msg)
}
// HandleOrder is the long method: about 100 lines, six jobs.
func HandleOrder(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(405)
return
}
var req orderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, 400, "bad json")
return
}
// validate the customer
if req.Email == "" || !strings.Contains(req.Email, "@") {
writeErr(w, 422, "invalid email")
return
}
if len(req.Items) == 0 {
writeErr(w, 422, "no items")
return
}
// validate the address
if req.Street == "" || req.City == "" || req.Zip == "" || req.Country == "" {
writeErr(w, 422, "address required")
return
}
mu.Lock()
defer mu.Unlock()
// compute the subtotal and check the stock
subtotal := 0.0
for _, it := range req.Items {
p, ok := Prices[it.SKU]
if !ok {
writeErr(w, 422, "unknown sku: "+it.SKU)
return
}
if it.Qty <= 0 {
writeErr(w, 422, "invalid qty: "+it.SKU)
return
}
if Stock[it.SKU] < it.Qty {
writeErr(w, 409, "out of stock: "+it.SKU)
return
}
subtotal += p * float64(it.Qty)
}
// discount: vip 10%, staff 30%, coupon 5 off except for staff
discount := 0.0
if req.Type == "vip" {
discount = subtotal * 0.10
} else if req.Type == "staff" {
discount = subtotal * 0.30
}
if req.Coupon == "WELCOME5" && req.Type != "staff" {
discount = discount + 5
}
// shipping
shipping := 0.0
switch req.Shipping {
case "standard":
if subtotal-discount >= 50 {
shipping = 0
} else if req.Country == "NL" {
shipping = 4.95
} else {
shipping = 9.95
}
case "express":
if req.Country == "NL" {
shipping = 9.95
} else {
shipping = 19.95
}
case "pickup":
shipping = 0
default:
writeErr(w, 422, "unknown shipping: "+req.Shipping)
return
}
total := subtotal - discount + shipping
// reserve the stock and save the order
for _, it := range req.Items {
Stock[it.SKU] -= it.Qty
}
id := len(Orders) + 1
Orders = append(Orders, map[string]any{
"id": id, "email": req.Email, "total": total,
"street": req.Street, "city": req.City, "zip": req.Zip, "country": req.Country,
"created": time.Now(),
})
// the same switch again, for the delivery estimate
eta := ""
switch req.Shipping {
case "standard":
eta = "3-5 days"
case "express":
eta = "1 day"
case "pickup":
eta = "same day"
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, `{"id":%d,"subtotal":%.2f,"discount":%.2f,"shipping":%.2f,"total":%.2f,"eta":%q}`,
id, subtotal, discount, shipping, total, eta)
}
// HandleQuote was copied from HandleOrder and trimmed: duplicate code.
func HandleQuote(w http.ResponseWriter, r *http.Request) {
var req orderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, 400, "bad json")
return
}
mu.Lock()
defer mu.Unlock()
subtotal := 0.0
for _, it := range req.Items {
p, ok := Prices[it.SKU]
if !ok {
writeErr(w, 422, "unknown sku: "+it.SKU)
return
}
subtotal += p * float64(it.Qty)
}
discount := 0.0
if req.Type == "vip" {
discount = subtotal * 0.10
} else if req.Type == "staff" {
discount = subtotal * 0.30
}
if req.Coupon == "WELCOME5" && req.Type != "staff" {
discount = discount + 5
}
shipping := 0.0
switch req.Shipping {
case "standard":
if subtotal-discount >= 50 {
shipping = 0
} else if req.Country == "NL" {
shipping = 4.95
} else {
shipping = 9.95
}
case "express":
if req.Country == "NL" {
shipping = 9.95
} else {
shipping = 19.95
}
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"subtotal":%.2f,"discount":%.2f,"shipping":%.2f,"total":%.2f}`,
subtotal, discount, shipping, subtotal-discount+shipping)
}Step 1: the safety net. The characterization test replays 14 requests, in order, against one state, and compares status code and body byte for byte. It passes on before/ today.
// Package labtest is the characterization (golden master) test shared by
// every version of the lab. It pins what the code does today, byte for byte,
// so each refactoring step can prove it changed structure and nothing else.
package labtest
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Handlers is what a version of the lab must expose.
type Handlers struct {
Order http.Handler
Quote http.Handler
Reset func()
}
type step struct {
name string
handler string // "order" or "quote"
method string
body string
wantCode int
wantBody string
}
const addrNL = `"street":"Main 1","city":"Utrecht","zip":"3511","country":"NL"`
const addrDE = `"street":"Hauptstr 2","city":"Berlin","zip":"10115","country":"DE"`
// The steps run in order against one state: stock taken by one step is gone
// for the next, exactly as in production.
var steps = []step{
{"regular, standard NL", "order", "POST",
`{"email":"a@x.io","customer_type":"regular","items":[{"sku":"BOOK","qty":2},{"sku":"MUG","qty":1}],` + addrNL + `,"shipping":"standard"}`,
201, `{"id":1,"subtotal":33.00,"discount":0.00,"shipping":4.95,"total":37.95,"eta":"3-5 days"}`},
{"vip gets 10% and free standard over 50", "order", "POST",
`{"email":"b@x.io","customer_type":"vip","items":[{"sku":"LAMP","qty":1},{"sku":"BOOK","qty":2}],` + addrDE + `,"shipping":"standard"}`,
201, `{"id":2,"subtotal":65.00,"discount":6.50,"shipping":0.00,"total":58.50,"eta":"3-5 days"}`},
{"staff 30%, coupon ignored, express DE", "order", "POST",
`{"email":"c@x.io","customer_type":"staff","coupon":"WELCOME5","items":[{"sku":"MUG","qty":2}],` + addrDE + `,"shipping":"express"}`,
201, `{"id":3,"subtotal":16.00,"discount":4.80,"shipping":19.95,"total":31.15,"eta":"1 day"}`},
{"coupon for regular, pickup", "order", "POST",
`{"email":"d@x.io","customer_type":"regular","coupon":"WELCOME5","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"pickup"}`,
201, `{"id":4,"subtotal":12.50,"discount":5.00,"shipping":0.00,"total":7.50,"eta":"same day"}`},
{"lamp already sold", "order", "POST",
`{"email":"e@x.io","customer_type":"regular","items":[{"sku":"LAMP","qty":1}],` + addrNL + `,"shipping":"standard"}`,
409, `{"error":"out of stock: LAMP"}`},
{"wrong method", "order", "GET", ``, 405, ``},
{"bad json", "order", "POST", `{`, 400, `{"error":"bad json"}`},
{"invalid email", "order", "POST",
`{"email":"nope","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"standard"}`,
422, `{"error":"invalid email"}`},
{"missing address", "order", "POST",
`{"email":"a@x.io","items":[{"sku":"BOOK","qty":1}],"shipping":"standard"}`,
422, `{"error":"address required"}`},
{"unknown sku", "order", "POST",
`{"email":"a@x.io","items":[{"sku":"PEN","qty":1}],` + addrNL + `,"shipping":"standard"}`,
422, `{"error":"unknown sku: PEN"}`},
{"unknown shipping", "order", "POST",
`{"email":"a@x.io","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"drone"}`,
422, `{"error":"unknown shipping: drone"}`},
{"quote does not reserve stock", "quote", "POST",
`{"customer_type":"regular","items":[{"sku":"BOOK","qty":2},{"sku":"MUG","qty":1}],"country":"NL","shipping":"standard"}`,
200, `{"subtotal":33.00,"discount":0.00,"shipping":4.95,"total":37.95}`},
{"quote keeps the old copy's quirk: unknown shipping costs 0", "quote", "POST",
`{"customer_type":"vip","items":[{"sku":"BOOK","qty":1}],"country":"NL","shipping":"drone"}`,
200, `{"subtotal":12.50,"discount":1.25,"shipping":0.00,"total":11.25}`},
{"quote never validated qty: negative amounts must print like %.2f", "quote", "POST",
`{"customer_type":"regular","items":[{"sku":"BOOK","qty":-1}],"country":"NL","shipping":"standard"}`,
200, `{"subtotal":-12.50,"discount":0.00,"shipping":4.95,"total":-7.55}`},
}
// Run replays every step against h and fails on the first difference.
func Run(t *testing.T, h Handlers) {
t.Helper()
h.Reset()
for _, s := range steps {
target := h.Order
if s.handler == "quote" {
target = h.Quote
}
req := httptest.NewRequest(s.method, "/"+s.handler, strings.NewReader(s.body))
rec := httptest.NewRecorder()
target.ServeHTTP(rec, req)
if rec.Code != s.wantCode || rec.Body.String() != s.wantBody {
t.Fatalf("%s:\n got %d %s\n want %d %s", s.name, rec.Code, rec.Body.String(), s.wantCode, s.wantBody)
}
}
}package before
import (
"net/http"
"testing"
"academy/code-smells-refactoring/labtest"
)
func TestCharacterization(t *testing.T) {
labtest.Run(t, labtest.Handlers{
Order: http.HandlerFunc(HandleOrder),
Quote: http.HandlerFunc(HandleQuote),
Reset: Reset,
})
}Step 2: encapsulate the global data. Move Prices, Stock and Orders into a Catalog and an Orders type with methods (Encapsulate Variable, Encapsulate Collection). Run go test ./...: green.
Step 3: introduce Money. Replace float64 with Money in cents (Replace Primitive with Object) and give it MarshalJSON that prints two decimals. Green, because every test amount is exact in cents; if the catalogue had prices like 0.333, this step would change rounding and the test would tell you.
Step 4: extract Address. The four strings become one type (Extract Class), and country == "NL" moves into Address.Domestic() (Move Function, curing feature envy). Green.
Step 5: name the numbers and decompose the discount. 0.10, 0.30, 5 and "WELCOME5" become constants; the if/else becomes CustomerType.Discount with acceptsCoupon (Replace Magic Literal, Decompose Conditional). Green.
Step 6: replace both shipping switches with polymorphism. One ShippingMethod interface, three types, one map. The ETA switch disappears because ETA() sits next to Cost(). Green.
Step 7: one copy of the pricing rules. Extract Pricer.Price (a pure query) and call it from both handlers. The test catches a divergence that the copy had introduced: HandleQuote charges 0 for an unknown shipping method instead of failing. A refactoring keeps it; Service.Quote falls back to pickup{} (Introduce Special Case) with a comment, and fixing it becomes its own ticket.
Step 8: Split Phase in the handler. Decode into a PlaceOrder command, call Service.Place, encode. The first attempt used json.NewEncoder, which adds a trailing newline; the byte-exact test failed; json.Marshal plus w.Write fixed it. Green.
The end state, file by file:
// Package after is the lab's end state: the same behaviour as package before,
// reached through small named refactorings, each run against labtest.
package after
import "fmt"
// Money replaces float64 (Replace Primitive with Object): integer cents, no
// float drift, one place that knows how money prints.
type Money int64
// Cents builds Money from a cent amount.
func Cents(c int64) Money { return Money(c) }
// Percent returns p percent of m, truncated to the cent.
func (m Money) Percent(p int64) Money { return m * Money(p) / 100 }
func (m Money) String() string {
sign := ""
if m < 0 {
sign, m = "-", -m
}
return fmt.Sprintf("%s%d.%02d", sign, m/100, m%100)
}
// MarshalJSON keeps the wire format of the old handler: a bare number with two decimals.
func (m Money) MarshalJSON() ([]byte, error) { return []byte(m.String()), nil }package after
// HomeCountry is where standard and express shipping are cheaper.
const HomeCountry = "NL"
// Address was a data clump of four strings (Extract Class, Introduce Parameter Object).
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Zip string `json:"zip"`
Country string `json:"country"`
}
// Complete reports whether every field is present.
func (a Address) Complete() bool {
return a.Street != "" && a.City != "" && a.Zip != "" && a.Country != ""
}
// Domestic moved here from the handler (Move Function: it was feature envy).
func (a Address) Domestic() bool { return a.Country == HomeCountry }package after
// CustomerType was a bare string compared in two copies of the same if/else.
type CustomerType string
const (
Regular CustomerType = "regular"
VIP CustomerType = "vip"
Staff CustomerType = "staff"
)
// Named constants replace the magic numbers 0.10, 0.30 and 5.
const (
vipDiscountPercent = 10
staffDiscountPercent = 30
welcomeCoupon = "WELCOME5"
)
var welcomeCouponValue = Cents(500)
// discountPercent is a lookup table: adding a customer type is one line.
var discountPercent = map[CustomerType]int64{VIP: vipDiscountPercent, Staff: staffDiscountPercent}
// Discount is Decompose Conditional applied to the old if/else plus coupon rule.
func (t CustomerType) Discount(subtotal Money, coupon string) Money {
d := subtotal.Percent(discountPercent[t])
if t.acceptsCoupon(coupon) {
d += welcomeCouponValue
}
return d
}
func (t CustomerType) acceptsCoupon(coupon string) bool {
return coupon == welcomeCoupon && t != Staff
}package after
// ShippingMethod replaces the two switches on the shipping string
// (Replace Conditional with Polymorphism). A new method is a new type
// plus one map entry; no switch to hunt down.
type ShippingMethod interface {
Cost(net Money, to Address) Money
ETA() string
}
const freeShippingFrom = Money(5000)
type standard struct{}
func (standard) Cost(net Money, to Address) Money {
switch {
case net >= freeShippingFrom:
return 0
case to.Domestic():
return Cents(495)
default:
return Cents(995)
}
}
func (standard) ETA() string { return "3-5 days" }
type express struct{}
func (express) Cost(_ Money, to Address) Money {
if to.Domestic() {
return Cents(995)
}
return Cents(1995)
}
func (express) ETA() string { return "1 day" }
// pickup is also the Special Case used by the quote endpoint for unknown names.
type pickup struct{}
func (pickup) Cost(Money, Address) Money { return 0 }
func (pickup) ETA() string { return "same day" }
var shippingMethods = map[string]ShippingMethod{
"standard": standard{},
"express": express{},
"pickup": pickup{},
}
// ShippingMethodFor returns the method or a validation error.
func ShippingMethodFor(name string) (ShippingMethod, error) {
m, ok := shippingMethods[name]
if !ok {
return nil, invalid("unknown shipping: " + name)
}
return m, nil
}package after
import "sync"
// Line is one SKU and a quantity.
type Line struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
// Catalog encapsulates the former global maps (Encapsulate Variable,
// Encapsulate Collection): nobody outside can write prices or stock.
type Catalog struct {
mu sync.Mutex
prices map[string]Money
stock map[string]int
}
// NewCatalog returns the demo catalogue used by the lab.
func NewCatalog() *Catalog {
return &Catalog{
prices: map[string]Money{"BOOK": Cents(1250), "MUG": Cents(800), "LAMP": Cents(4000)},
stock: map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1},
}
}
// Price is a query: it never changes state.
func (c *Catalog) Price(sku string) (Money, bool) {
c.mu.Lock()
defer c.mu.Unlock()
p, ok := c.prices[sku]
return p, ok
}
// Check validates lines in the same order the old handler did:
// per line, unknown SKU, then quantity, then stock.
func (c *Catalog) Check(lines []Line) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.check(lines)
}
func (c *Catalog) check(lines []Line) error {
for _, l := range lines {
if _, ok := c.prices[l.SKU]; !ok {
return invalid("unknown sku: " + l.SKU)
}
if l.Qty <= 0 {
return invalid("invalid qty: " + l.SKU)
}
if c.stock[l.SKU] < l.Qty {
return conflict("out of stock: " + l.SKU)
}
}
return nil
}
// Reserve is the modifier: check and decrement under one lock.
func (c *Catalog) Reserve(lines []Line) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.check(lines); err != nil {
return err
}
for _, l := range lines {
c.stock[l.SKU] -= l.Qty
}
return nil
}package after
// Quote is the result record of pricing (immutable in practice, so a data
// class is fine here: Fowler's exception for Split Phase results).
type Quote struct {
Subtotal Money `json:"subtotal"`
Discount Money `json:"discount"`
Shipping Money `json:"shipping"`
Total Money `json:"total"`
}
// Pricer is the single copy of the pricing rules that both endpoints use
// (the duplicate code is gone; Separate Query from Modifier: no side effects).
type Pricer struct{ Catalog *Catalog }
// Price computes a quote. Callers validate lines first.
func (p Pricer) Price(lines []Line, t CustomerType, coupon string, ship ShippingMethod, to Address) (Quote, error) {
var q Quote
for _, l := range lines {
price, ok := p.Catalog.Price(l.SKU)
if !ok {
return Quote{}, invalid("unknown sku: " + l.SKU)
}
q.Subtotal += price * Money(l.Qty)
}
q.Discount = t.Discount(q.Subtotal, coupon)
q.Shipping = ship.Cost(q.Subtotal-q.Discount, to)
q.Total = q.Subtotal - q.Discount + q.Shipping
return q, nil
}package after
import (
"strings"
"sync"
"time"
)
// PlaceOrder is the command (Introduce Parameter Object for nine loose fields).
type PlaceOrder struct {
Email string `json:"email"`
Type CustomerType `json:"customer_type"`
Lines []Line `json:"items"`
Address // embedded: the JSON keeps its flat shape
Shipping string `json:"shipping"`
Coupon string `json:"coupon"`
}
// Order is what we store.
type Order struct {
ID int
Email string
Total Money
Address Address
Created time.Time
}
// Placed is returned to the HTTP layer.
type Placed struct {
ID int `json:"id"`
Quote
ETA string `json:"eta"`
}
// Orders replaces the global slice (Encapsulate Collection).
type Orders struct {
mu sync.Mutex
list []Order
}
func (o *Orders) add(ord Order) int {
o.mu.Lock()
defer o.mu.Unlock()
ord.ID = len(o.list) + 1
o.list = append(o.list, ord)
return ord.ID
}
// All returns a copy; callers cannot append behind our back.
func (o *Orders) All() []Order {
o.mu.Lock()
defer o.mu.Unlock()
return append([]Order(nil), o.list...)
}
// Service is the use case. Each step is one named function call.
type Service struct {
Catalog *Catalog
Orders *Orders
Pricer Pricer
Now func() time.Time
}
// NewService wires the lab's in-memory pieces.
func NewService() *Service {
c := NewCatalog()
return &Service{Catalog: c, Orders: &Orders{}, Pricer: Pricer{Catalog: c}, Now: time.Now}
}
// Place validates, prices, reserves and saves, in the old order of checks.
func (s *Service) Place(cmd PlaceOrder) (Placed, error) {
if err := validateCustomer(cmd); err != nil {
return Placed{}, err
}
if err := s.Catalog.Check(cmd.Lines); err != nil {
return Placed{}, err
}
ship, err := ShippingMethodFor(cmd.Shipping)
if err != nil {
return Placed{}, err
}
q, err := s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)
if err != nil {
return Placed{}, err
}
if err := s.Catalog.Reserve(cmd.Lines); err != nil {
return Placed{}, err
}
id := s.Orders.add(Order{Email: cmd.Email, Total: q.Total, Address: cmd.Address, Created: s.Now()})
return Placed{ID: id, Quote: q, ETA: ship.ETA()}, nil
}
func validateCustomer(cmd PlaceOrder) error {
switch {
case cmd.Email == "" || !strings.Contains(cmd.Email, "@"):
return invalid("invalid email")
case len(cmd.Lines) == 0:
return invalid("no items")
case !cmd.Address.Complete():
return invalid("address required")
}
return nil
}
// Quote prices without side effects. Unknown shipping costs nothing: the old
// HandleQuote copy did that, the characterization test pins it, and changing
// it is a behaviour change for its own commit, not part of this refactoring.
func (s *Service) Quote(cmd PlaceOrder) (Quote, error) {
ship, err := ShippingMethodFor(cmd.Shipping)
if err != nil {
ship = pickup{}
}
return s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)
}package after
// Kind says which HTTP status an error maps to, without the domain importing net/http.
type Kind int
const (
Invalid Kind = iota + 1
Conflict
)
// Error is a domain error with a kind and a message for the client.
type Error struct {
Kind Kind
Msg string
}
func (e *Error) Error() string { return e.Msg }
func invalid(msg string) error { return &Error{Invalid, msg} }
func conflict(msg string) error { return &Error{Conflict, msg} }package after
import (
"encoding/json"
"errors"
"net/http"
)
// Handler is now a thin adapter: decode, call one use case, encode.
type Handler struct{ Svc *Service }
// Order handles POST /orders.
func (h Handler) Order(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var cmd PlaceOrder
if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
writeJSON(w, http.StatusBadRequest, errorBody{"bad json"})
return
}
placed, err := h.Svc.Place(cmd)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusCreated, placed)
}
// Quote handles POST /quote.
func (h Handler) Quote(w http.ResponseWriter, r *http.Request) {
var cmd PlaceOrder
if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
writeJSON(w, http.StatusBadRequest, errorBody{"bad json"})
return
}
q, err := h.Svc.Quote(cmd)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, q)
}
type errorBody struct {
Error string `json:"error"`
}
var statusOf = map[Kind]int{Invalid: http.StatusUnprocessableEntity, Conflict: http.StatusConflict}
func writeError(w http.ResponseWriter, err error) {
var e *Error
if !errors.As(err, &e) {
writeJSON(w, http.StatusInternalServerError, errorBody{"internal error"})
return
}
writeJSON(w, statusOf[e.Kind], errorBody{e.Msg})
}
func writeJSON(w http.ResponseWriter, code int, v any) {
body, err := json.Marshal(v) // Marshal, not Encoder: no trailing newline, same bytes as before
if err != nil {
code, body = http.StatusInternalServerError, []byte(`{"error":"internal error"}`)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_, _ = w.Write(body)
}package after
import (
"net/http"
"testing"
"academy/code-smells-refactoring/labtest"
)
func TestCharacterization(t *testing.T) {
h := &Handler{Svc: NewService()}
labtest.Run(t, labtest.Handlers{
Order: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.Order(w, r) }),
Quote: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.Quote(w, r) }),
Reset: func() { h.Svc = NewService() },
})
}
func TestMoneyIsExact(t *testing.T) {
if got := Cents(1600).Percent(30).String(); got != "4.80" {
t.Fatalf("got %s", got)
}
}Step 9: measure.
| Metric | Before | After |
|---|---|---|
| Longest function | HandleOrder, about 110 lines | Service.Place, about 25 lines |
| Copies of the pricing rules | 2 | 1 (Pricer.Price) |
| Switches on the shipping string | 3 (two in HandleOrder, one in HandleQuote) | 0 (one map lookup) |
| Package-level mutable variables | 4 | 0 (shippingMethods and discountPercent are read-only tables) |
| Files touched by "free shipping from 60" | 1 file, 2 places | 1 constant |
| Files touched by "add courier shipping" | 3 switches | 1 new type + 1 map entry |
| Characterization test | PASS | PASS (same 14 cases, byte-exact) |
Step 10 (optional): run the linters on both. golangci-lint run --enable funlen,gocognit,dupl,mnd,gochecknoglobals ./... should report the long function, the duplicated block, the magic numbers and the globals in before/; in after/ expect only the deliberate read-only lookup tables (shippingMethods, discountPercent, statusOf) and the named cent amounts inside shipping.go, which you can accept or move to constants. (Not run for this page.)
Part B: Laravel
The same domain in a Laravel 13 app (PHP 8.4). php is not run here; the files are reviewed, not executed. The routes are Route::post('/orders', [OrderController::class, 'store']) in routes/api.php, with Product (sku, price decimal:2, stock) and Order models; Order needs $fillable for Order::create() in the after code.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
// The smelly starting point of the Laravel lab: one controller method that
// validates, prices, ships, reserves stock, saves and emails.
class OrderController extends Controller
{
public function store(Request $request): JsonResponse
{
// validate
$data = $request->validate([
'email' => 'required|email',
'customer_type' => 'nullable|string',
'items' => 'required|array|min:1',
'items.*.sku' => 'required|string',
'items.*.qty' => 'required|integer|min:1',
'street' => 'required', 'city' => 'required', 'zip' => 'required', 'country' => 'required',
'shipping' => 'required|string',
'coupon' => 'nullable|string',
]);
return DB::transaction(function () use ($data) {
// subtotal and stock, floats for money
$subtotal = 0.0;
foreach ($data['items'] as $item) {
$product = Product::where('sku', $item['sku'])->lockForUpdate()->first();
if (! $product) {
return response()->json(['error' => 'unknown sku: '.$item['sku']], 422);
}
if ($product->stock < $item['qty']) {
return response()->json(['error' => 'out of stock: '.$item['sku']], 409);
}
$subtotal += $product->price * $item['qty'];
}
// discount
$discount = 0.0;
if (($data['customer_type'] ?? 'regular') == 'vip') {
$discount = $subtotal * 0.10;
} elseif (($data['customer_type'] ?? 'regular') == 'staff') {
$discount = $subtotal * 0.30;
}
if (($data['coupon'] ?? null) == 'WELCOME5' && ($data['customer_type'] ?? 'regular') != 'staff') {
$discount += 5;
}
// shipping
switch ($data['shipping']) {
case 'standard':
$shipping = $subtotal - $discount >= 50 ? 0 : ($data['country'] == 'NL' ? 4.95 : 9.95);
break;
case 'express':
$shipping = $data['country'] == 'NL' ? 9.95 : 19.95;
break;
case 'pickup':
$shipping = 0;
break;
default:
return response()->json(['error' => 'unknown shipping: '.$data['shipping']], 422);
}
$total = $subtotal - $discount + $shipping;
// reserve stock
foreach ($data['items'] as $item) {
Product::where('sku', $item['sku'])->decrement('stock', $item['qty']);
}
// save
$order = new Order;
$order->email = $data['email'];
$order->street = $data['street'];
$order->city = $data['city'];
$order->zip = $data['zip'];
$order->country = $data['country'];
$order->total = $total;
$order->save();
// email, inside the transaction, on the request path
Mail::raw('Thanks for order #'.$order->id, fn ($m) => $m->to($data['email'])->subject('Your order'));
// the same switch again
$eta = match ($data['shipping']) {
'standard' => '3-5 days',
'express' => '1 day',
'pickup' => 'same day',
};
return response()->json([
'id' => $order->id,
'subtotal' => round($subtotal, 2),
'discount' => round($discount, 2),
'shipping' => round($shipping, 2),
'total' => round($total, 2),
'eta' => $eta,
], 201);
});
}
}Step 1: characterization tests against the old controller. Note the exact floats: the old code returns 33.0, not 33.
<?php
namespace Tests\Feature;
use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
// Characterization tests: written against the OLD controller first, kept green
// after every refactoring step. They pin today's behaviour, quirks included.
final class OrderCharacterizationTest extends TestCase
{
use RefreshDatabase;
private const ADDRESS_NL = ['street' => 'Main 1', 'city' => 'Utrecht', 'zip' => '3511', 'country' => 'NL'];
private const ADDRESS_DE = ['street' => 'Hauptstr 2', 'city' => 'Berlin', 'zip' => '10115', 'country' => 'DE'];
protected function setUp(): void
{
parent::setUp();
Mail::fake();
Queue::fake();
Product::insert([
['sku' => 'BOOK', 'price' => '12.50', 'stock' => 10],
['sku' => 'MUG', 'price' => '8.00', 'stock' => 3],
['sku' => 'LAMP', 'price' => '40.00', 'stock' => 1],
]);
}
public function test_regular_customer_standard_shipping_in_nl(): void
{
$this->postJson('/api/orders', [
'email' => 'a@x.io', 'customer_type' => 'regular', 'shipping' => 'standard',
'items' => [['sku' => 'BOOK', 'qty' => 2], ['sku' => 'MUG', 'qty' => 1]],
...self::ADDRESS_NL,
])->assertCreated()->assertExactJson([
'id' => 1, 'subtotal' => 33.0, 'discount' => 0.0, 'shipping' => 4.95, 'total' => 37.95, 'eta' => '3-5 days',
]);
$this->assertSame(8, Product::firstWhere('sku', 'BOOK')->stock);
}
public function test_vip_gets_ten_percent_and_free_standard_shipping_over_fifty(): void
{
$this->postJson('/api/orders', [
'email' => 'b@x.io', 'customer_type' => 'vip', 'shipping' => 'standard',
'items' => [['sku' => 'LAMP', 'qty' => 1], ['sku' => 'BOOK', 'qty' => 2]],
...self::ADDRESS_DE,
])->assertCreated()->assertJson(['discount' => 6.5, 'shipping' => 0, 'total' => 58.5]);
}
public function test_staff_discount_ignores_the_coupon(): void
{
$this->postJson('/api/orders', [
'email' => 'c@x.io', 'customer_type' => 'staff', 'coupon' => 'WELCOME5', 'shipping' => 'express',
'items' => [['sku' => 'MUG', 'qty' => 2]],
...self::ADDRESS_DE,
])->assertCreated()->assertJson(['discount' => 4.8, 'shipping' => 19.95, 'total' => 31.15, 'eta' => '1 day']);
}
public function test_unknown_customer_type_is_treated_as_regular(): void
{
$this->postJson('/api/orders', [
'email' => 'd@x.io', 'customer_type' => 'gold', 'shipping' => 'pickup',
'items' => [['sku' => 'BOOK', 'qty' => 1]],
...self::ADDRESS_NL,
])->assertCreated()->assertJson(['discount' => 0, 'total' => 12.5]);
}
public function test_out_of_stock_is_a_conflict_and_changes_nothing(): void
{
$this->postJson('/api/orders', [
'email' => 'e@x.io', 'shipping' => 'standard',
'items' => [['sku' => 'BOOK', 'qty' => 1], ['sku' => 'LAMP', 'qty' => 2]],
...self::ADDRESS_NL,
])->assertConflict()->assertExactJson(['error' => 'out of stock: LAMP']);
$this->assertSame(10, Product::firstWhere('sku', 'BOOK')->stock);
$this->assertDatabaseCount('orders', 0);
}
public function test_unknown_sku_and_unknown_shipping_are_unprocessable(): void
{
$this->postJson('/api/orders', [
'email' => 'f@x.io', 'shipping' => 'standard', 'items' => [['sku' => 'PEN', 'qty' => 1]], ...self::ADDRESS_NL,
])->assertUnprocessable()->assertExactJson(['error' => 'unknown sku: PEN']);
$this->postJson('/api/orders', [
'email' => 'f@x.io', 'shipping' => 'drone', 'items' => [['sku' => 'BOOK', 'qty' => 1]], ...self::ADDRESS_NL,
])->assertUnprocessable()->assertExactJson(['error' => 'unknown shipping: drone']);
}
}Step 2: Money and Address value objects. Watch the wire format: the old code sends 33.0; jsonSerialize(): float plus dividing by 100.0 keeps it a float. (PHP was not run for this page; the tests are reviewed, not executed.)
<?php
namespace App\Domain\Orders;
use JsonSerializable;
// Replace Primitive with Object: integer cents instead of float.
final readonly class Money implements JsonSerializable
{
private function __construct(public int $cents) {}
public static function cents(int $cents): self
{
return new self($cents);
}
// Products store price as a decimal:2 column, which Eloquent casts to a string like "12.50".
public static function fromDecimal(string $amount): self
{
return new self((int) round(((float) $amount) * 100));
}
public static function zero(): self
{
return new self(0);
}
public function plus(self $other): self
{
return new self($this->cents + $other->cents);
}
public function minus(self $other): self
{
return new self($this->cents - $other->cents);
}
public function times(int $qty): self
{
return new self($this->cents * $qty);
}
public function percent(int $p): self
{
return new self(intdiv($this->cents * $p, 100));
}
public function atLeast(self $other): bool
{
return $this->cents >= $other->cents;
}
// Keeps the old wire format: a float such as 33.0, as round() produced before.
public function jsonSerialize(): float
{
return $this->cents / 100.0;
}
}<?php
namespace App\Domain\Orders;
// The data clump street/city/zip/country becomes one value object.
final readonly class Address
{
public const HOME_COUNTRY = 'NL';
public function __construct(
public string $street,
public string $city,
public string $zip,
public string $country,
) {}
public static function fromArray(array $data): self
{
return new self($data['street'], $data['city'], $data['zip'], $data['country']);
}
public function isDomestic(): bool
{
return $this->country === self::HOME_COUNTRY;
}
}Step 3: enums with behaviour replace the string type codes and both switches.
<?php
namespace App\Domain\Orders;
// A backed enum replaces the 'vip' / 'staff' strings compared in if/elseif chains.
enum CustomerType: string
{
case Regular = 'regular';
case Vip = 'vip';
case Staff = 'staff';
private const WELCOME_COUPON = 'WELCOME5';
private const WELCOME_COUPON_CENTS = 500;
public function discount(Money $subtotal, ?string $coupon): Money
{
$discount = $subtotal->percent($this->discountPercent());
return $this->acceptsCoupon($coupon)
? $discount->plus(Money::cents(self::WELCOME_COUPON_CENTS))
: $discount;
}
private function discountPercent(): int
{
return match ($this) {
self::Regular => 0,
self::Vip => 10,
self::Staff => 30,
};
}
private function acceptsCoupon(?string $coupon): bool
{
return $coupon === self::WELCOME_COUPON && $this !== self::Staff;
}
}<?php
namespace App\Domain\Orders;
// Replace Conditional with Polymorphism, PHP 8.1+ style: each case owns its rules.
// The single match per method is exhaustive; adding a case without a rule is a
// fatal UnhandledMatchError in tests, not a silent zero.
enum ShippingMethod: string
{
case Standard = 'standard';
case Express = 'express';
case Pickup = 'pickup';
private const FREE_FROM_CENTS = 5000;
public function cost(Money $net, Address $to): Money
{
return match ($this) {
self::Standard => match (true) {
$net->atLeast(Money::cents(self::FREE_FROM_CENTS)) => Money::zero(),
$to->isDomestic() => Money::cents(495),
default => Money::cents(995),
},
self::Express => Money::cents($to->isDomestic() ? 995 : 1995),
self::Pickup => Money::zero(),
};
}
public function eta(): string
{
return match ($this) {
self::Standard => '3-5 days',
self::Express => '1 day',
self::Pickup => 'same day',
};
}
}Step 4: a pure pricing function and a parameter object.
<?php
namespace App\Domain\Orders;
// Result record of pricing; immutable, so being "just data" is fine here.
final readonly class PriceQuote
{
public function __construct(
public Money $subtotal,
public Money $discount,
public Money $shipping,
public Money $total,
) {}
/**
* Pure calculation (Separate Query from Modifier): no database, no side effects.
*
* @param list<array{price: Money, qty: int}> $lines
*/
public static function calculate(array $lines, CustomerType $type, ?string $coupon, ShippingMethod $method, Address $to): self
{
$subtotal = array_reduce($lines, fn (Money $sum, array $l) => $sum->plus($l['price']->times($l['qty'])), Money::zero());
$discount = $type->discount($subtotal, $coupon);
$shipping = $method->cost($subtotal->minus($discount), $to);
return new self($subtotal, $discount, $shipping, $subtotal->minus($discount)->plus($shipping));
}
public function toArray(): array
{
return [
'subtotal' => $this->subtotal,
'discount' => $this->discount,
'shipping' => $this->shipping,
'total' => $this->total,
];
}
}<?php
namespace App\Domain\Orders;
// Introduce Parameter Object: one typed command instead of an untyped array.
// shippingName stays a string on purpose: the old controller rejected an unknown
// method only after the stock checks, and the characterization test pins that order.
final readonly class PlaceOrderData
{
/** @param list<array{sku: string, qty: int}> $items */
public function __construct(
public string $email,
public CustomerType $type,
public array $items,
public Address $address,
public string $shippingName,
public ?string $coupon,
) {}
}Step 5: the Form Request, the Action and a renderable exception. Unknown customer types are still treated as regular and unknown shipping is still rejected after the stock checks, because the tests say so; tightening that with Rule::enum is a later, behaviour-changing commit.
<?php
namespace App\Http\Requests;
use App\Domain\Orders\Address;
use App\Domain\Orders\CustomerType;
use App\Domain\Orders\PlaceOrderData;
use Illuminate\Foundation\Http\FormRequest;
// Validation leaves the controller (Extract Class into Laravel's slot for it).
final class PlaceOrderRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'email' => ['required', 'email'],
'customer_type' => ['nullable', 'string'],
'items' => ['required', 'array', 'min:1'],
'items.*.sku' => ['required', 'string'],
'items.*.qty' => ['required', 'integer', 'min:1'],
'street' => ['required'], 'city' => ['required'], 'zip' => ['required'], 'country' => ['required'],
'shipping' => ['required', 'string'],
'coupon' => ['nullable', 'string'],
];
}
public function toData(): PlaceOrderData
{
return new PlaceOrderData(
email: $this->validated('email'),
// unknown types were treated as regular before; keep it (tighten later, in its own commit)
type: CustomerType::tryFrom($this->validated('customer_type') ?? '') ?? CustomerType::Regular,
items: $this->validated('items'),
address: Address::fromArray($this->safe()->only(['street', 'city', 'zip', 'country'])),
shippingName: $this->validated('shipping'),
coupon: $this->validated('coupon'),
);
}
}<?php
namespace App\Domain\Orders;
use Illuminate\Http\JsonResponse;
use RuntimeException;
// A renderable exception: Laravel calls render() automatically, and throwing
// inside DB::transaction rolls the transaction back.
final class OrderRejected extends RuntimeException
{
private function __construct(string $message, private readonly int $status)
{
parent::__construct($message);
}
public static function unknownSku(string $sku): self
{
return new self('unknown sku: '.$sku, 422);
}
public static function outOfStock(string $sku): self
{
return new self('out of stock: '.$sku, 409);
}
public static function unknownShipping(string $name): self
{
return new self('unknown shipping: '.$name, 422);
}
public function render(): JsonResponse
{
return response()->json(['error' => $this->getMessage()], $this->status);
}
}<?php
namespace App\Actions;
use App\Domain\Orders\Money;
use App\Domain\Orders\OrderRejected;
use App\Domain\Orders\PlaceOrderData;
use App\Domain\Orders\PriceQuote;
use App\Domain\Orders\ShippingMethod;
use App\Events\OrderPlaced;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
// The use case. Each line is one named step; the controller no longer knows them.
final class PlaceOrder
{
/** @return array{order: Order, quote: PriceQuote, method: ShippingMethod} */
public function handle(PlaceOrderData $data): array
{
return DB::transaction(function () use ($data) {
$products = $this->lockProducts($data->items);
$lines = array_map(fn (array $i) => [
'price' => Money::fromDecimal($products[$i['sku']]->price),
'qty' => $i['qty'],
], $data->items);
$method = ShippingMethod::tryFrom($data->shippingName)
?? throw OrderRejected::unknownShipping($data->shippingName);
$quote = PriceQuote::calculate($lines, $data->type, $data->coupon, $method, $data->address);
foreach ($data->items as $item) {
$products[$item['sku']]->decrement('stock', $item['qty']);
}
$order = Order::create([
'email' => $data->email,
'street' => $data->address->street,
'city' => $data->address->city,
'zip' => $data->address->zip,
'country' => $data->address->country,
'total' => $quote->total->cents / 100.0,
]);
OrderPlaced::dispatch($order);
return ['order' => $order, 'quote' => $quote, 'method' => $method];
});
}
/** @return array<string, Product> keyed by SKU, rows locked FOR UPDATE */
private function lockProducts(array $items): array
{
$products = Product::whereIn('sku', array_column($items, 'sku'))
->lockForUpdate()
->get()
->keyBy('sku')
->all();
foreach ($items as $item) {
$product = $products[$item['sku']] ?? throw OrderRejected::unknownSku($item['sku']);
if ($product->stock < $item['qty']) {
throw OrderRejected::outOfStock($item['sku']);
}
}
return $products;
}
}Step 6: the thin controller.
<?php
namespace App\Http\Controllers;
use App\Actions\PlaceOrder;
use App\Http\Requests\PlaceOrderRequest;
use Illuminate\Http\JsonResponse;
// The controller translates HTTP into one call and back. Nothing else.
final class OrderController extends Controller
{
public function store(PlaceOrderRequest $request, PlaceOrder $placeOrder): JsonResponse
{
['order' => $order, 'quote' => $quote, 'method' => $method] = $placeOrder->handle($request->toData());
return response()->json([
'id' => $order->id,
...$quote->toArray(),
'eta' => $method->eta(),
], 201);
}
}Step 7: the behaviour change, on purpose and last. Sending the email synchronously inside the transaction is a real problem (a mail-server timeout holds row locks), but moving it changes timing, so it is its own commit with its own test (Queue::fake() / Event::fake()), after all refactoring commits are merged.
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
final class OrderPlaced
{
use Dispatchable, SerializesModels;
public function __construct(public Order $order) {}
}<?php
namespace App\Listeners;
use App\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Support\Facades\Mail;
// The email left the transaction and the request path. This is a behaviour
// change (timing), so it ships in its own commit with its own test, after the
// refactoring commits.
final class SendOrderConfirmation implements ShouldQueueAfterCommit
{
public function handle(OrderPlaced $event): void
{
Mail::raw('Thanks for order #'.$event->order->id, fn ($m) => $m->to($event->order->email)->subject('Your order'));
}
}Step 8: let the tools hold the line. Add PHPStan (start at the level the code passes, generate a baseline, raise one level per PR), Rector with deadCode and codeQuality sets in --dry-run on CI, and Pint for style so refactoring diffs contain no whitespace noise.
Common misconceptions
| Belief | Reality |
|---|---|
| Refactoring is any clean-up or rewrite | It is a sequence of small behaviour-preserving moves; a broken build for days is restructuring |
| A smell proves the code is bad | "smells don't always indicate a problem"; it is a reason to look |
| Comments are a smell | Comments used "as a deodorant" are; "why" comments are "a sweet smell" |
| Every switch should be polymorphism | Fowler renamed the smell Repeated Switches in 2018; one switch is fine |
| All duplication must be removed at once | Rule of three; accidental duplication between owners stays |
| Smaller classes are always better | Over-splitting causes Shotgun Surgery; Inline Class is a refactoring too |
| You need a refactoring sprint | Most refactoring is preparatory, comprehension or litter-pickup, minutes long |
| You can refactor without tests if you are careful | Without a net you cannot know behaviour was kept; write characterization tests first |
| Pint refactors code | Pint fixes style only; Rector and IDEs perform refactorings |
| Changing an API between services is refactoring | It is a contract change; use versioning or expand/contract |
| Data classes are always wrong | Result records, DTOs and immutable values are Fowler's explicit exception |
| Go has no inheritance, so inheritance smells do not apply | Embedding reproduces Refused Bequest and Middle Man; the cure is a field instead of embedding |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition | Change structure, not observable behaviour, in small steps, tests green after each |
| Smell | "a surface indication that usually corresponds to a deeper problem"; look, then decide |
| Families | Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers (refactoring.guru) |
| 2018 changes | New: Mysterious Name, Global Data, Mutable Data, Loops; renamed: Long Function, Repeated Switches, Lazy Element, Insider Trading |
| Top moves | Extract Function, Rename, Move Function, Extract Class, Introduce Parameter Object, Replace Conditional with Polymorphism |
| Timing | Preparatory, comprehension, litter-pickup, TDD refactor step; rule of three for duplication |
| Two hats | Never refactor and change behaviour in the same step or commit |
| Legacy code | Characterization (golden master) tests first |
| Large changes | Parallel Change (expand, migrate, contract), Branch by Abstraction |
| Anti-patterns | Blob, Lava Flow, Golden Hammer, Poltergeists, Boat Anchor, Cut-and-Paste, Spaghetti, Magic Numbers, Cargo Cult |
| Architecture smells | Cyclic, Hub-Like, Unstable Dependency, God Component, Shared Database, Distributed Monolith |
| Go tools | gofmt -r, gopls code actions, vet, staticcheck, golangci-lint (funlen, gocognit, dupl, mnd, unused, unparam) |
| PHP tools | PHPStan levels 0–10 + baseline, Rector sets and levels, Pint for style, PhpStorm refactorings |
| Microservices | Refactor inside, version contracts across; extract with Strangler Fig after in-process moves |
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 two conditions make a code change a refactoring? Must-know
Answer
Answer: Observable behaviour is unchanged, and it is done as a sequence of small, behaviour-preserving steps with the system working after each one. See Definition.
2 — Divergent change and shotgun surgery: which is which? Must-know
Answer
Answer: Divergent change: one module, many reasons to change. Shotgun surgery: one reason to change, many modules to edit. See Divergent Change and Shotgun Surgery.
3 — Why did Fowler rename "Switch Statements" to "Repeated Switches" in 2018? Good to know
Answer
Answer: Polymorphism is no longer underused and modern switches are richer; the real problem is the same switching logic in several places, where adding a case means finding all of them. See Switch Statements.
4 — You find the same 6 lines in two places. Do you extract them? Must-know
Answer
Answer: Not yet, unless both copies have the same owner and must always change together. Apply the rule of three, and keep accidental duplication between different owners. See Rule of three.
5 — A legacy controller has no tests and you must change it. What is your first step? Must-know
Answer
Answer: Write characterization tests that pin its current behaviour (exact responses, side effects), make them pass on the old code, then refactor. See The safety net.
6 — During a refactoring, the characterization test reveals that the quote endpoint charges 0 for unknown shipping. What do you do? Important
Answer
Answer: Keep the behaviour (the refactoring must not change it), document it, and change it later in a separate commit after a product decision. See the lab, step 7.
7 — Which golangci-lint linters would you enable to find long functions, duplication, magic numbers and globals? Important
Answer
Answer: funlen / gocognit, dupl, mnd (and goconst), gochecknoglobals. See Go tooling.
8 — Is Laravel Pint a refactoring tool? Must-know
Answer
Answer: No. It is a code style fixer built on PHP CS Fixer; it never changes structure. Rector and PhpStorm perform refactorings; PHPStan is the safety net. See PHP tooling.
9 — How does Refused Bequest appear in Go, which has no inheritance, and how do you fix it? Good to know
Answer
Answer: Through struct embedding: the outer type exports every method of the embedded one and has to refuse some. Replace the embedding with a field and forward only the methods you want (Replace Superclass with Delegate). See Refused Bequest.
10 — What is the difference between a code smell and an anti-pattern? Must-know
Answer
Answer: A smell is a local symptom in code that suggests a problem; an anti-pattern is a recurring design solution that looks reasonable but has more drawbacks than benefits, documented together with a refactored solution. See Anti-patterns.
11 — Why is renaming a field in a published event not a refactoring? Must-know
Answer
Answer: Other services observe the event; its shape is behaviour. Use versioning or Parallel Change (expand, migrate, contract). See Microservices.
12 — Name the three architectural smells Arcan detects from the dependency graph and one cure for each. Good to know
Answer
Answer: Cyclic Dependency (extract the shared concept or invert one edge with an interface), Hub-Like Dependency (split the hub by purpose), Unstable Dependency (depend toward stability, hide the volatile part behind an interface). See Architectural smells.
Glossary
| Term | Meaning |
|---|---|
| Refactoring (noun) | A behaviour-preserving change to internal structure that makes code easier to understand and cheaper to modify |
| Refactoring (verb) | Restructuring software by applying a series of refactorings without changing observable behaviour |
| Restructuring | Any rearrangement of code; refactoring is the disciplined, small-step kind |
| Code smell | A quick-to-spot surface sign that usually points to a deeper design problem |
| Anti-pattern | A recurring solution that looks right but has more drawbacks than benefits, documented with a refactored solution |
| Architectural smell | A smell in the dependency structure between components (cycles, hubs, unstable dependencies) |
| Bloaters / OO Abusers / Change Preventers / Dispensables / Couplers | refactoring.guru's five smell families |
| Long Method / Long Function | A function too long to understand at a glance; cured by Extract Function |
| Large Class | A type with too many fields and responsibilities |
| Primitive Obsession | Domain concepts kept in primitives ("stringly typed") |
| Long Parameter List | Too many parameters, often flags |
| Data Clumps | Values that always travel together and want to be a type |
| Switch Statements / Repeated Switches | The same conditional on a type code in several places |
| Temporary Field | A field set only in some circumstances |
| Refused Bequest | A subtype that does not want what it inherits |
| Alternative Classes with Different Interfaces | Types doing the same job with different method names |
| Divergent Change | One module changed for many unrelated reasons |
| Shotgun Surgery | One change requiring many small edits across modules |
| Parallel Inheritance Hierarchies | Adding a subclass in one hierarchy forces one in another |
| Comments (smell) | Comments used as deodorant for unclear code |
| Duplicate Code / Duplicated Code | The same logic in more than one place |
| Lazy Class / Lazy Element | A class or function that no longer earns its keep |
| Data Class | Fields and accessors only; behaviour lives elsewhere |
| Dead Code | Code that is never executed |
| Speculative Generality | Abstraction for needs that never came |
| Feature Envy | A function more interested in another module's data than its own |
| Inappropriate Intimacy / Insider Trading | Modules that know too much about each other's internals |
| Message Chains | Navigating a chain of objects, coupling the client to the structure |
| Middle Man | A type that mostly delegates |
| Incomplete Library Class | A library type missing a needed method |
| Mysterious Name / Global Data / Mutable Data / Loops | The four smells added in Fowler's 2018 edition |
| Extract Function / Inline Function | Name a fragment as a function / put a function's body back at the call sites |
| Extract Variable | Name a sub-expression |
| Change Function Declaration | Rename a function or change its parameters |
| Move Function / Move Field | Move behaviour or data to the module that owns it |
| Replace Temp with Query | Turn a temporary variable into a function |
| Introduce Parameter Object | Group parameters into one type |
| Preserve Whole Object | Pass the object instead of values pulled out of it |
| Remove Flag Argument | Replace a boolean switch parameter with explicit functions |
| Replace Primitive with Object | Wrap a primitive in a domain type |
| Replace Conditional with Polymorphism | Replace a switch on type with one implementation per case |
| Replace Type Code with Subclasses | Turn a type code into types (aliases: Extract Subclass, Replace Type Code with State/Strategy) |
| Decompose Conditional | Extract condition and branches into named functions |
| Extract Class / Inline Class | Split a type in two / merge a type back |
| Pull Up Method / Push Down Method | Move a method to the parent / to the subclasses |
| Replace Superclass with Delegate | Replace inheritance with a field and forwarding (alias Replace Inheritance with Delegation) |
| Introduce Special Case | A type for a special value with default behaviour (alias Introduce Null Object) |
| Separate Query from Modifier | Split a function that both answers and changes state |
| Encapsulate Collection | Never hand out the internal collection; return copies |
| Encapsulate Variable | Wrap data access in functions to control and track it |
| Split Phase | Separate two stages with an intermediate data structure |
| Combine Functions into Class | Group functions that share data into a type |
| Hide Delegate / Remove Middle Man | Add / remove forwarding methods |
| Replace Magic Literal | Name a literal constant |
| Two hats | Adding behaviour and refactoring are separate activities |
| Rule of three | Refactor duplication on the third occurrence |
| Preparatory / comprehension / litter-pickup / planned / long-term refactoring | Fowler's refactoring workflows |
| Opportunistic refactoring | Refactoring whenever you see the need, by whoever sees it; the camp-site rule |
| Red-Green-Refactor | TDD's cycle: failing test, passing code, clean-up |
| Characterization test / Golden Master | A test that pins current behaviour of legacy code |
| Parallel Change (expand and contract) | Change an interface in three phases: expand, migrate, contract |
| Branch by Abstraction | Replace a component behind an interface while releasing regularly |
| Strangler Fig | Gradually replace a legacy system by routing functionality to new code |
| God Object / Blob | One class that monopolises behaviour |
| Spaghetti Code / Cut-and-Paste Programming / Golden Hammer / Lava Flow / Poltergeists / Boat Anchor | AntiPatterns (1998) development anti-patterns |
| Magic Number | An unexplained literal |
| Cargo Cult Programming | Ritual structure with no real purpose |
| Cyclic / Hub-Like / Unstable Dependency, God Component | Architectural smells detected by Arcan |
| Shared Database | Several services reading and writing the same tables |
| Distributed Monolith | Services that must change and deploy together |
| Technical debt | The extra cost of change caused by today's structure |
| gofmt / gopls / go vet / staticcheck / golangci-lint | Go formatter with rewrite rules, language server with refactoring code actions, and static analysers |
| PHPStan / baseline / Rector / Laravel Pint / PhpStorm | PHP static analyser with levels and a baseline file, automated refactoring rules, style fixer, IDE with refactorings |
References
- Martin Fowler, refactoring.com (definition and "Refactoring is a part of day-to-day programming") and the online catalog of refactorings, including the cards Extract Function, Replace Conditional with Polymorphism, Introduce Special Case, Separate Query from Modifier, Replace Superclass with Delegate, Replace Type Code with Subclasses, Encapsulate Collection, Introduce Parameter Object, Move Function, Extract Class, Decompose Conditional, Replace Temp with Query, Pull Up Method
- Martin Fowler and Kent Beck, "Bad Smells in Code", chapter 3 of Refactoring, 2nd ed. (Addison-Wesley, 2018), InformIT excerpt
- Martin Fowler, bliki: CodeSmell, DefinitionOfRefactoring, RefactoringMalapropism, OpportunisticRefactoring, TestDrivenDevelopment, ParallelChange (Danilo Sato), BranchByAbstraction
- Martin Fowler, Workflows of Refactoring (infodeck, 2014); An example of preparatory refactoring; Strangler Fig
- refactoring.guru: Code Smells (the five families and every smell page, e.g. Long Method, Feature Envy), When to refactor (secondary summary of Fowler)
- W. Brown, R. Malveau, H. McCormick, T. Mowbray, AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis (Wiley, 1998), the authors' site: catalog, development catalog, Lava Flow
- Joshua Kerievsky, Refactoring to Patterns (Addison-Wesley, 2004), Industrial Logic book page
- D. Sas, P. Avgeriou, U. Uyumaz, "On the evolution and impact of Architectural Smells: an industrial case study", 2022, arXiv:2203.08702 (reports Arcelli Fontana et al.'s Arcan definitions)
- Chris Richardson, Shared database pattern, microservices.io
- Wikipedia (secondary): Code refactoring (Opdyke, Griswold), Anti-pattern (Koenig 1995), Rule of three, Characterization test, Magic number, Cargo cult programming
- Go: gofmt, gopls code transformation features, staticcheck checks, golangci-lint linters and linter settings
- PHP: PHPStan rule levels, Rector documentation and set lists, PhpStorm: code refactoring
- Laravel 13: Pint, HTTP tests, Validation: Form Requests, Errors: renderable exceptions, Events: ShouldQueueAfterCommit, Queries: pessimistic locking