Clean Code Principles: Naming, Small Units, Pure Functions & Side Effects, DRY/YAGNI/KISS and Their Failure Modes
"It is more important that code be easy to read than easy to write." — Google Go Style Guide, "Clarity" (google.github.io/styleguide/go/guide)
Summary: Clean code is code a stranger can read, change and test without fear: intention-revealing names, small units that sit at one level of abstraction, functions whose result depends only on their arguments, side effects pushed to the edge, and duplication removed only when it is the same knowledge, not just the same shape. Focus: Every rule practitioners quote (naming, formatting, small functions, argument lists, pure functions, command-query separation, idempotence, immutability, guard clauses, comments, dead code, DRY, WET, rule of three, YAGNI, KISS, boy scout rule, deep modules), each with its failure mode when it is applied mechanically, the Go and PHP/Laravel tools that enforce it, and a lab that cleans one pricing function in both languages. Learning goal: Apply each rule, say what it costs, recognise when it has been over-applied (shallow micro-functions, wrong abstractions, speculative interfaces), and wire the mechanical parts into CI so that review time goes to design instead of style.
This page is the complete reference for the day-to-day craft rules. It does not re-teach its neighbours. The catalogue of smells and the refactoring moves that cure them are on Code Smells & Refactoring; the five class-level principles are on SOLID (function-level single responsibility here is the small sibling of SRP); coupling, cohesion and information hiding as theory are on Design Quality; message chains and the Law of Demeter are on Composing Objects; paradigms such as functional programming are on Programming Paradigms; the test pyramid, test doubles and TDD are on Testing Strategy & TDD; Go error values in depth are on Errors, panic, recover & defer; Go linting and project layout are on Project Layout, Linting & Build; Go test mechanics are on Testing & Benchmarking; and dependency direction at architecture level is on Clean, Hexagonal & Component Principles.
Page map
| If you are looking for | Go to |
|---|---|
| The rules, their failure modes and the tool that checks each, in three tables | Everything in one minute |
| Why code has to be cheap to read, and the three beliefs to drop first | Why clean code exists |
| Kelly Johnson, Meyer, Beck, Hunt and Thomas, Fowler, Martin, Ousterhout, Sonar | Where it comes from |
| Names: intention-revealing, searchable, consistent vocabulary, Go and PHP conventions | Naming |
| gofmt, Laravel Pint, PSR-12, PER, SQL layout | Formatting |
| Small functions, one level of abstraction, single responsibility at function level | Small functions |
| Argument count, flag, null and output arguments | Arguments |
| Pure functions, side effects, referential transparency | Pure functions |
| Command-query separation and idempotence | CQS and idempotence |
| Immutability and value semantics | Immutability |
| Functional core, imperative shell | Functional core |
| Guard clauses, early return, exceptions vs error values | Error handling vs happy path |
| Comments, self-documenting code, dead code | Comments and dead code |
| DRY, WET, rule of three | DRY |
| YAGNI, KISS, speculative generality, premature abstraction | YAGNI and KISS |
| Boy scout rule | Boy scout rule |
| Framework at the edge, dependency direction, cohesion and coupling | Framework at the edge |
| Deep modules vs shallow modules (Ousterhout against Martin) | Deep modules |
| Cyclomatic and cognitive complexity, gocyclo, gocognit, phpmd | Complexity metrics |
| FIRST principles, fast and independent tests, test readability | Clean tests |
| Linters, formatters and CI config for Go and PHP | Tooling and mechanics |
| The code review checklist | Code review checklist |
| Fat handler, boolean parameter, helper everyone imports, wrong abstraction | Solving the classic problems |
| Which rule wins when two disagree | Choosing |
| One process to many services | In architecture |
| A 52-line Go function and a Laravel controller cleaned in steps with tests | Lab |
| Wrong beliefs, cheat sheet, interview questions, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The rules, in one table. Every row is unpacked later; the last column is what goes wrong when the rule becomes a religion.
| Rule | In plain words | Tiny example | Failure mode when overdone |
|---|---|---|---|
| Intention-revealing names | The name says what and why, not how | overdueInvoices, not list2 | Names so long they hide the logic; or Java-style AbstractInvoiceProcessorFactoryImpl in Go |
| Small functions | Each function does one thing at one level | Quote calls subtotalOf, tierDiscount, shippingFee | Shallow micro-functions that must be read together (entanglement) |
| Few arguments | The list is short and every argument is a real input | NewClient(cfg Config) | A Config struct that becomes a bag of unrelated flags |
| Pure functions | Same arguments, same result, nothing else changes | PriceWithTax(net, percent) | Threading the clock and the logger through ten layers |
| Command-query separation | A method either changes state or answers, not both | Increment() and Value() | Splitting Pop() on a stack or an atomic GetAndIncrement where atomicity matters |
| Guard clauses | Fail fast at the top; keep the happy path at the margin | if cancelled { return ErrCancelled } | Eight returns in a 15-line function; cleanup forgotten (use defer) |
| Comments say why | Code says what; comments say why and what is surprising | // Spec: ISO 4217 minor units | No comments at all, so every decision has to be reverse-engineered |
| DRY | One authoritative representation of each piece of knowledge | One Cents.String() | Merging look-alikes that change for different reasons (wrong abstraction) |
| Rule of three | Tolerate two copies, extract at the third | Third copy of the tax rule | Copy-pasting ten times because "it is only the second" |
| YAGNI | Do not build what is not needed yet | No PaymentGateway interface for one gateway | Never leaving a seam, so a needed change becomes a rewrite |
| KISS | Prefer the simplest thing that works | A switch, not a plugin registry | "Simple" meaning "naive": ignoring a known requirement |
| Boy scout rule | Leave the file a little cleaner than you found it | Rename one variable while fixing a bug | Drive-by refactors that bury the real change in the diff |
The numbers worth remembering. They come from the tools, not from folklore; defaults are the ones the tool documents.
| Tool | What it counts | Default threshold or level |
|---|---|---|
gocyclo (and golangci-lint gocyclo) | Cyclomatic complexity: 1 plus each if, for, case, and each && or or-operator | golangci-lint reports at 30 by default and recommends 10 to 20 |
gocognit (and golangci-lint gocognit) | Cognitive complexity: breaks in linear flow, with nesting penalties | 30 by default, 10 to 20 recommended |
| funlen | Function length | 60 lines and 40 statements |
| nestif | Complexity of nested if statements | 5 |
| PHPStan | Types and bugs, in cumulative levels | 11 levels, 0 (loosest) to 10 (strictest); default 0 |
| Psalm | Types and bugs, in error levels | 1 (strictest) to 8 (most lenient); default 2 |
| PHPMD | Size and complexity rules | CyclomaticComplexity reports at 10, ExcessiveParameterList at 10, NPathComplexity at 200 |
Which tool owns which job.
| Job | Go | PHP and Laravel |
|---|---|---|
| Formatting | gofmt (also goimports, gofumpt as stricter formatters) | Laravel Pint (preset laravel, also psr12, per, symfony, empty), PSR-12 and PER Coding Style |
| Style and naming review | Effective Go, Go Code Review Comments, Google Go Style Guide, revive | PSR-12, PER, Laravel conventions, PHPStorm inspections |
| Bugs and types | go vet, staticcheck, compiler | PHPStan, Psalm |
| Complexity and size | gocyclo, gocognit, funlen, nestif via golangci-lint | PHPMD (CyclomaticComplexity, NPathComplexity, ExcessiveParameterList) |
| Duplicates and dead code | dupl, unused, unparam | PHPStan dead-code checks at its higher levels |
| Tests | go test -race, table tests | PHPUnit, Laravel HTTP tests |
Why clean code exists
Code is read many more times than it is written, and most of the reading happens when something is already broken. The rules on this page are all ways of lowering the cost of that reading: a name that answers a question before it is asked, a function you can hold in your head, a result you can predict without running anything.
| Without the discipline | With the discipline |
|---|---|
| A change needs a guided tour from the one person who remembers | A newcomer finds the right place by searching a name |
| A bug fix touches six copies and misses one | The rule lives in one place |
| Every test needs a database, a clock and a mail server | Rules are pure and tested with plain values |
| Review comments are about braces and spacing | Review comments are about behaviour and design |
| A "quick fix" adds a flag argument and one more branch | The branch has a name, a test and a home |
Everyday picture: the kitchen. A professional kitchen is organised so a new cook finds the salt without asking. Ingredients are labelled (names), stations do one job (small units), a recipe card gives the same dish from the same inputs (pure functions), only the pass talks to the dining room (side effects at the edge), and nobody keeps three jars of the same spice in three places with three different labels (DRY). A kitchen with a poster that says "never keep two jars of anything" and a cook who merges salt and sugar into one jar "to avoid duplication" is the failure mode of this whole chapter.
Three common misunderstandings, up front
- "Clean code means short code." Clean means cheap to read and change. A 40-line function that does one thing in a straight line is cleaner than ten 4-line functions you must read in a fixed order.
- "The rules are laws." They are heuristics with failure modes, and the authors disagree. Robert C. Martin's Clean Code and John Ousterhout's A Philosophy of Software Design give opposite advice on method length and on comments; the Choosing section shows the disagreement and how to decide.
- "A formatter and a linter make code clean." They remove one whole class of argument (style) and catch a few smells. They cannot tell you that a name is misleading or that an abstraction is the wrong one.
Where it comes from
Year Who / what What it gave us
1 1938 "Keep it Short and Simple" attested (Minneapolis Star) early form of KISS (Wikipedia, secondary)
2 1960 Kelly Johnson, Lockheed Skunk Works; U.S. Navy "KISS": simplicity as a design goal
3 1988 Bertrand Meyer, Object-Oriented Software Construction command-query separation (CQS)
4 1999 Hunt and Thomas, The Pragmatic Programmer DRY: single authoritative representation of knowledge
5 1999 Fowler (with Beck), Refactoring rule of three, "Three strikes and you refactor"
6 ~2000 Extreme Programming (Beck, Jeffries, Hendrickson) YAGNI; the four rules of simple design
7 2008 Robert C. Martin, Clean Code naming, small functions, comments (positions as quoted by Ousterhout)
8 Go gofmt, Effective Go, Go Code Review Comments the formatter and naming conventions as language culture
9 2018 John Ousterhout, A Philosophy of Software Design deep modules; the strongest published counter-argument to Clean Code
10 2023 SonarSource white paper v1.7 on Cognitive Complexity a metric for understandability rather than testabilityRows 1 and 2 are from the Wikipedia KISS page (secondary); row 10 is the date printed on the white paper. The years in rows 3 to 7 and 9 are commonly cited publication years that were not checked on a saved page, and no claim below depends on them.
What each source actually says, from the pages saved for this chapter:
- Kent Beck's four rules of simple design, as Martin Fowler lists them: "Passes the tests", "Reveals intention", "No duplication", "Fewest elements". Fowler adds: "The rules are in priority order, so 'passes the tests' takes priority over 'reveals intention'". The rules are the root of most of this page, and their order is the answer to many arguments below.
- Command-query separation. Fowler: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." He credits Bertrand Meyer.
- YAGNI. Fowler: "It's a statement that some capability we presume our software needs in the future should not be built now because 'you aren't gonna need it'." The phrase came from a conversation between Kent Beck and Chet Hendrickson on the C3 project.
- DRY. As stated on Wikipedia (secondary): "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system", formulated by Andy Hunt and Dave Thomas in The Pragmatic Programmer. Note the word knowledge: it is not "every line of code".
- Rule of three. Wikipedia (secondary): "two instances of similar code do not require refactoring, but when similar code is used three times, it should be extracted", popularised by Fowler in Refactoring and attributed to Don Roberts.
- Go's own style sources. Effective Go, the wiki page Go Code Review Comments, and the Google Go Style Guide (Guide, Decisions, Best practices) are the three documents Go teams cite in review. The Go proverbs add "Clear is better than clever." and "A little copying is better than a little dependency."
- PHP's style sources. PSR-12 (the extended coding style guide) and its successor PER Coding Style, whose text says it "extends, expands and replaces PSR-12". Laravel's own docs say Pint is "an opinionated PHP code style fixer for minimalists" built on PHP CS Fixer.
- Ousterhout against Martin. In the published exchange between the two (github.com/johnousterhout/aposd-vs-clean-code) Ousterhout writes that Clean Code's "advice on method length is so extreme that it encourages programmers to create teeny-tiny methods that suffer from both shallow interfaces and entanglement". The Deep modules section covers it.
- Cognitive Complexity. The SonarSource white paper (version 1.7, 29 August 2023) says it describes "a new metric" to remedy cyclomatic complexity's shortcomings and "produce a measurement that more accurately reflects the relative difficulty of understanding, and therefore of maintaining methods, classes, and applications".
Not read first-hand. Clean Code itself (2008), The Pragmatic Programmer and A Philosophy of Software Design are books; this page quotes them only through pages that were fetched (Fowler's bliki, Wikipedia, Ousterhout's own site and the exchange above). Chapter and page numbers below come from those secondary quotations or are omitted.
The concept catalogue
One block per rule. The order follows how a reviewer reads a diff: names and layout first, then function shape, then arguments, then behaviour (purity, state, errors), then duplication and speculation, then module and test level. The pieces of Go and PHP used in the blocks are all in the lab, which compiles and tests them.
Naming: intention-revealing names, searchable names, consistent vocabulary Must-know
In plain words: a good name answers "what is this, and why does it exist?" so the reader does not have to open the body to find out.
Common misunderstanding: "Longer names are always clearer." Go's Code Review Comments say the opposite for small scopes: "Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex." The rule that reconciles both: "the further from its declaration that a name is used, the more descriptive the name must be."
Definition: three separate properties, often mixed up.
| Property | Meaning | Test |
|---|---|---|
| Intention-revealing names | The name states purpose, not mechanism or type | Could you delete the comment above it? |
| Searchable names | The name is unique enough to find with grep or an IDE search | Does searching 5000 find the shipping rule, or does freeShippingThreshold? |
| Consistent vocabulary | One word per concept across the codebase | Is it fetch, get, load and retrieve for the same thing in four files? |
Timeline of a bad name (a ticket reads "free shipping from 50"):
Step Who What happens
1 Mon Dev A writes `if t < 5000 { s = 700 }` (t = total in cents, s = shipping)
2 Tue Dev B grep "shipping" finds nothing: the word is not in the file
3 Wed Dev B adds a second rule with a hard-coded 5000 in the invoice code
4 Thu Support "free shipping" differs between cart and invoice; ticket reopened
5 Fri Dev C spends the day proving the two numbers are the same factReal scenarios: a column called status that holds five different workflows; a Manager or Helper or Utils class that collects everything nobody could name; data, info and item as parameter names; isNotDisabled double negatives; a userList that is really a map.
Go conventions (all from Effective Go and Go Code Review Comments, saved under pipeline/sources/clean-code-principles/):
| Topic | Rule | Example |
|---|---|---|
| Multiword names | "the convention in Go is to use MixedCaps or mixedCaps rather than underscores" | orderTotal, OrderTotal, not order_total |
| Getters | "it's neither idiomatic nor necessary to put Get into the getter's name"; a field owner has a getter Owner and a setter SetOwner | obj.Owner(), not obj.GetOwner() |
| Package names | "short, concise, evocative", lower case, single word, no underscores | bytes, http, not byte_utils |
| Package and symbol together | The package name is always visible, so do not repeat it; Google's guide says a package that exports one type named after itself uses New for the constructor | ledger.New, not ledger.NewLedger |
| Receivers | One or two letters, a reflection of the type; never me, this or self | func (c *Client) Do() |
| One-method interfaces | The method name plus -er | Reader, Notifier |
| Initialisms | Keep a consistent case (ID, URL, HTTP) | userID, not userId |
PHP and Laravel conventions (PSR-1, PSR-12, Laravel docs): classes in StudlyCaps (PSR-12 says to read PSR-1's term as PascalCase), methods in camelCase, constants in upper case with underscores, enum cases in PascalCase (as in the lab's Tier::Gold), tables plural snake_case and models singular by Eloquent convention.
Consistent vocabulary in practice:
// Three words for one idea, in three packages: the reader must learn all three.
func (s *Store) Fetch(id string) (Order, error) { /* ... */ }
func (r *Repo) Get(id string) (Order, error) { /* ... */ }
func (c *Cache) Retrieve(id string) (Order, error) { /* ... */ }
// One word, chosen once and written in a short glossary in the package doc.
func (s *Store) Order(id string) (Order, error) { /* ... */ }
func (r *Repo) Order(id string) (Order, error) { /* ... */ }
func (c *Cache) Order(id string) (Order, error) { /* ... */ }// Before: what is $d, what is 7, what is "p"?
$d = Order::where('s', 'p')->where('c', '<', now()->subDays(7))->get();
// After: the query names the business concept; the number has one name and one home.
$staleUnpaidOrders = Order::query()->unpaid()->olderThan(self::UNPAID_GRACE_DAYS)->get();What a linter can and cannot do. revive is available in golangci-lint as a configurable replacement for golint; PHPStorm and PHPStan can flag unknown names, not bad ones. Nothing detects a misleading name. That is a review job and the first item of the code review checklist.
Formatting: gofmt, Laravel Pint, PSR-12 Must-know
In plain words: formatting is a solved problem: pick the standard, run the tool, never discuss it again.
Common misunderstanding: "Formatting is cosmetic." It is the part of readability that a machine can guarantee. The Go blog lists what gofmt buys: code that is easier to write ("never worry about minor formatting concerns"), to read ("when all code looks the same you need not mentally convert others' formatting style"), to maintain ("diffs show only the real changes") and "uncontroversial: never have a debate about spacing or brace position ever again!".
Definition and tools:
| Ecosystem | Tool | What it does | Command |
|---|---|---|---|
| Go | gofmt | Rewrites source to the one canonical layout; flags -l list files that differ, -d print diffs, -w overwrite, -s simplify ([]T{T{}, T{}} becomes []T{{}, {}}) | gofmt -l . must print nothing |
| Go | goimports, gofumpt | Stricter formatters; golangci-lint v2 runs them under formatters: | golangci-lint fmt |
| PHP | PSR-12 | The extended coding style: 4 spaces, LF endings, soft line limit 120 ("The soft limit on line length MUST be 120 characters"), no hard limit | rules, not a tool |
| PHP | PER Coding Style | The evolving successor; its text says it "extends, expands and replaces PSR-12" | rules, not a tool |
| Laravel | Laravel Pint | "an opinionated PHP code style fixer for minimalists", built on PHP CS Fixer, installed with new Laravel apps; presets laravel (default), per, psr12, symfony, empty | ./vendor/bin/pint --test in CI, ./vendor/bin/pint locally |
| SQL | none standard | Team convention (below) | review |
Timeline of a style argument that never happens:
Step Where What happens
1 editor on save gofmt / Pint rewrites the file
2 pre-commit hook gofmt -l . and pint --test fail the commit if a file differs
3 CI the same two commands fail the build
4 review nobody comments on spacing; the diff shows only real changesPint configuration (a pint.json in the project root; the default needs none):
{
"preset": "laravel"
}SQL formatting has no gofmt, so write the convention down. Keywords upper-case, one clause per line, aliases that mean something, joins with explicit ON, a comment for the non-obvious rule:
-- Hard to read and hard to diff: one line, aliases a/b/c, implicit join.
select a.id,sum(b.q*b.p) t from orders a,order_items b where a.id=b.order_id and a.status='paid' and a.created_at>now()-interval '30 days' group by a.id having sum(b.q*b.p)>5000;
-- Clean: one clause per line, names that say what they are, the rule is visible.
SELECT o.id AS order_id,
SUM(i.quantity * i.unit_price) AS subtotal_cents
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id
WHERE o.status = 'paid'
AND o.created_at > now() - INTERVAL '30 days'
GROUP BY o.id
HAVING SUM(i.quantity * i.unit_price) > 5000; -- 5000 cents: the free-shipping thresholdWhat formatting does not decide: line wrapping inside a call, naming, and file layout. Go's guide, for example, leaves long argument lists to judgement and prefers option structs over very long lines. A formatter makes style uniform; it cannot make it good.
Small functions: one level of abstraction, single responsibility at function level Must-know
In plain words: a function should read like one paragraph that stays at one altitude: either it describes the steps of a business rule, or it does the byte-level work, not both.
Common misunderstanding: "A function must be at most N lines." Fowler's bliki: "The argument that makes most sense to me, however, is the separation between intention and implementation. If you have to spend effort into looking at a fragment of code to figure out what it's doing, then you should extract it into a function and name the function after that 'what'." Length is a smell indicator, not the rule; Fowler himself says "Any function more than half-a-dozen lines of code starts to smell to me" and also that "size isn't important".
Definition: three ideas that are usually taught together.
| Idea | Meaning | Test |
|---|---|---|
| Small functions | Short enough to hold in your head | Can you name it without "and"? |
| One level of abstraction | Every statement in the function is at the same conceptual height | Does a line about "tax" sit next to a line about strings.Builder? |
| Single responsibility at function level | One reason to change (the small cousin of SRP) | If the tax rule changes and the email text changes, do you edit the same function? |
Before and after from the lab. The "before" is one function whose body mixes validation, three pricing rules, shipping, tax, a clock read and a notification, with single-letter names and a pointer used as an output slot:
package before
import (
"errors"
"time"
)
// Notify is a package-level hook that tests and callers patch: hidden global state.
var Notify func(to, msg string)
// Item is one order line. P is the unit price in cents, Q the quantity.
type Item struct{ P, Q int }
// Proc computes the order total.
// d is the discount kind, f turns on express shipping, c is a coupon code,
// exp is when the coupon stops working and res receives the total in cents.
func Proc(it []Item, d string, f bool, c string, exp time.Time, res *int) error {
// check the list
if len(it) == 0 {
return errors.New("empty")
}
// add up
t := 0
for _, i := range it {
if i.Q > 0 {
if i.P >= 0 {
t += i.P * i.Q
} else {
return errors.New("bad price")
}
} else {
return errors.New("bad qty")
}
}
x := 0
if d == "gold" {
x = t * 10 / 100
} else if d == "silver" {
x = t * 5 / 100
}
y := 0
if c == "WELCOME" {
if time.Now().Before(exp) {
if t >= 2000 {
y = 500
}
}
}
n := t - x - y
s := 0
if d != "gold" {
if t < 5000 {
s = 700
}
}
if f {
s += 1500
}
v := n * 20 / 100
r := n + s + v
if r > 50000 {
if Notify != nil {
Notify("ops", "big order")
}
}
*res = r
return nil
}The "after" is a method that reads as the rule it implements; every step is a named function in the same file, and the clock arrives as an argument:
// Package after is the clean version of before: a pure core (Quote) that
// takes everything it needs as arguments and returns everything it computes.
package after
import (
"errors"
"time"
)
// Business rules live in named constants: one place per fact.
const (
goldDiscountPercent = 10
silverDiscountPercent = 5
taxPercent = 20
welcomeCouponCode = "WELCOME"
welcomeCouponOff = Cents(500)
welcomeCouponMinimum = Cents(2000)
standardShipping = Cents(700)
freeShippingThreshold = Cents(5000)
expressSurcharge = Cents(1500)
// LargeOrderThreshold is the total above which operations is told.
LargeOrderThreshold = Cents(50000)
)
var (
ErrNoItems = errors.New("order has no items")
ErrBadQuantity = errors.New("quantity must be positive")
ErrBadPrice = errors.New("unit price must not be negative")
)
type Tier string
const (
TierStandard Tier = ""
TierSilver Tier = "silver"
TierGold Tier = "gold"
)
type Speed int
const (
SpeedStandard Speed = iota
SpeedExpress
)
type LineItem struct {
UnitPrice Cents
Quantity int
}
// Coupon's zero value means "no coupon": callers never pass nil.
type Coupon struct {
Code string
ExpiresAt time.Time
}
type Order struct {
Items []LineItem
Tier Tier
Speed Speed
Coupon Coupon
}
type Quote struct {
Subtotal, Discount, Shipping, Tax, Total Cents
}
// Quote prices an order. It is pure: the clock arrives as an argument, nothing
// global is read or written, and the same arguments always give the same result.
func (o Order) Quote(now time.Time) (Quote, error) {
subtotal, err := subtotalOf(o.Items)
if err != nil {
return Quote{}, err
}
discount := tierDiscount(o.Tier, subtotal) + couponDiscount(o.Coupon, subtotal, now)
net := subtotal - discount
shipping := shippingFee(o.Tier, o.Speed, subtotal)
tax := net * taxPercent / 100
return Quote{
Subtotal: subtotal,
Discount: discount,
Shipping: shipping,
Tax: tax,
Total: net + shipping + tax,
}, nil
}
func subtotalOf(items []LineItem) (Cents, error) {
if len(items) == 0 {
return 0, ErrNoItems
}
var sum Cents
for _, it := range items {
if it.Quantity <= 0 {
return 0, ErrBadQuantity
}
if it.UnitPrice < 0 {
return 0, ErrBadPrice
}
sum += it.UnitPrice * Cents(it.Quantity)
}
return sum, nil
}
func tierDiscount(tier Tier, subtotal Cents) Cents {
switch tier {
case TierGold:
return subtotal * goldDiscountPercent / 100
case TierSilver:
return subtotal * silverDiscountPercent / 100
default:
return 0
}
}
func couponDiscount(c Coupon, subtotal Cents, now time.Time) Cents {
if c.Code != welcomeCouponCode {
return 0
}
if !now.Before(c.ExpiresAt) {
return 0
}
if subtotal < welcomeCouponMinimum {
return 0
}
return welcomeCouponOff
}
func shippingFee(tier Tier, speed Speed, subtotal Cents) Cents {
var fee Cents
if tier != TierGold && subtotal < freeShippingThreshold {
fee = standardShipping
}
if speed == SpeedExpress {
fee += expressSurcharge
}
return fee
}Real scenarios: a 300-line main that parses flags, reads a file, transforms it and writes a report; a Laravel controller store() with validation, pricing, DB::transaction, mail and a JSON response; a Go HTTP handler that decodes, validates, queries, formats and logs in one body.
When a long function is fine: a linear main that only wires dependencies, a switch that is a lookup table, a generated parser, and a table-driven test with many cases. funlen (60 lines, 40 statements by default) will still flag them, so the linter needs an exclusion for tests and wiring, not a refactor.
How to extract safely: Code Smells & Refactoring owns the moves (Extract Function, Replace Temp with Query, Decompose Conditional). The loop is always: add or run the characterization test, extract one function, run the tests, commit.
The failure mode is covered under Deep modules: cut too far and you get shallow micro-functions that must be read together.
Arguments: count, flag, null and output arguments Must-know
In plain words: every argument is something the caller must know and get right; fewer, clearer arguments mean fewer wrong calls.
Common misunderstanding: "Three arguments is the limit." The number is a proxy. What hurts is arguments of the same type in a row (host string, port int, useTLS bool, timeout time.Duration, retries int) that a caller can swap without a compile error, and booleans whose meaning is invisible at the call site (Render(r, true)).
Definition: four separate problems with one cure each.
| Problem | What it looks like | Why it hurts | Cure |
|---|---|---|---|
| Arguments count | NewClient(host, port, tls, timeout, retries) | Easy to swap, hard to extend | Option struct (Google Go best practices: "An option structure is a struct type that collects some or all of the arguments") or functional options; PHP: named arguments or a parameter object. PHPMD ExcessiveParameterList reports from 10 |
| Flag arguments | Render(report, detailed bool) | Fowler: "A flag argument is a kind of function argument that tells the function to carry out a different operation depending on its value" and "My general reaction to flag arguments is to avoid them" | Two functions named for what they do |
| Null arguments | Send(msg, nil) for "no cc list" | Every callee must check for nil; a forgotten check is a crash | Make the zero value meaningful (Coupon{} means no coupon), use an optional type or two overloads; PHP: nullable type only at the edge |
| Output arguments | Parse(s, &out) | The reader must guess which argument is written | Return the result (and an error) |
Timeline of a flag argument spreading:
Step Change Result
1 v1 Render(r Report) string one behaviour
2 v2 Render(r Report, detailed bool) string two behaviours in one body
3 v3 Render(r Report, detailed, html bool) string four combinations, two untested
4 v4 Render(r Report, detailed, html, csv bool) "html and csv" is undefinedIn Go and PHP. The snippet below shows all four cures with tests that prove the new functions equal the old ones:
// Package args shows how to shrink an argument list: split flag arguments,
// return results instead of filling pointers, collect options in a struct and
// let the zero value mean "default" instead of passing nil.
package args
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
type Report struct {
Title string
Rows []string
}
// RenderFlag is a flag argument: the boolean picks between two functions.
func RenderFlag(r Report, detailed bool) string {
if detailed {
return r.Title + "\n" + strings.Join(r.Rows, "\n")
}
return fmt.Sprintf("%s (%d rows)", r.Title, len(r.Rows))
}
// RenderSummary and RenderDetail say what they do at the call site.
func RenderSummary(r Report) string { return fmt.Sprintf("%s (%d rows)", r.Title, len(r.Rows)) }
func RenderDetail(r Report) string { return r.Title + "\n" + strings.Join(r.Rows, "\n") }
// ParseOut is an output argument: the reader must guess that out is written.
func ParseOut(s string, out *int) error {
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil {
return fmt.Errorf("parse %q: %w", s, err)
}
*out = n
return nil
}
// Parse returns what it computes.
func Parse(s string) (int, error) {
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil {
return 0, fmt.Errorf("parse %q: %w", s, err)
}
return n, nil
}
// NewClientLong has five positional arguments of similar types: easy to swap.
func NewClientLong(host string, port int, useTLS bool, timeout time.Duration, retries int) Client {
return Client{Host: host, Port: port, TLS: useTLS, Timeout: timeout, Retries: retries}
}
// Config is an option struct: fields are named at the call site and the zero
// value of each field means "use the default".
type Config struct {
Host string
Port int
TLS bool
Timeout time.Duration
Retries int
}
type Client struct {
Host string
Port int
TLS bool
Timeout time.Duration
Retries int
}
var ErrNoHost = errors.New("host is required")
func NewClient(cfg Config) (Client, error) {
if cfg.Host == "" {
return Client{}, ErrNoHost
}
if cfg.Port == 0 {
cfg.Port = 443
}
if cfg.Timeout == 0 {
cfg.Timeout = 5 * time.Second
}
return Client(cfg), nil
}// Laravel: named arguments make a call site readable without a parameter object.
$client = new ApiClient(host: 'api.example.test', timeout: 5, retries: 3);
// A flag argument split in two:
$report->renderSummary(); // not $report->render(detailed: false)
$report->renderDetail();
// Null argument: the nullable type belongs at the edge (a request field),
// the domain object receives a real value.
$expiresAt = $request->date('coupon_expires_at') ?? new DateTimeImmutable('@0');Real scenarios: http.Client has a Timeout field instead of a constructor argument, so the zero value works; Laravel's Mail::to($user)->send($mailable) replaces a function with eight arguments by a chain of named steps; a Go function with ctx context.Context first is the one positional argument everyone agrees on.
What prevents it: golangci-lint has no single "too many arguments" linter in the default set; reviewers and Google's guidance on option structures do the work, and unparam removes arguments nobody uses. In PHP, PHPMD's ExcessiveParameterList is the mechanical check.
Pure functions, side effects, referential transparency Must-know
In plain words: a pure function is a calculator: the same inputs always give the same answer, and nothing else in the world changes while it runs.
Common misunderstanding: "A function with no void return is pure." A function that reads time.Now(), a global, an environment variable or a database row is not pure even though it returns a value; and a function that logs is not pure even if its logic is. What matters is hidden inputs (the clock, globals, I/O) and hidden outputs (mutation, writes, logs).
Definition: a pure function returns a value that depends only on its arguments and has no side effects. A side effect is any observable change outside the function's return value: writing a field, a global or a file, calling an API, printing, reading the clock, generating a random number. Referential transparency is the consequence: a call can be replaced by its result without changing the program, so PriceWithTax(100, 20) can be replaced by 120 anywhere.
| Hidden input or output | Impure example | Pure replacement |
|---|---|---|
| Clock | time.Now() inside the rule | now time.Time argument |
| Randomness | rand.Intn inside the rule | the generated value as an argument (a seeded generator is deterministic, but consuming it changes its state, so it is not pure) |
| Global or package variable | TaxPercent read inside the function | a taxPercent argument or a field of a value |
| Environment | os.Getenv in a rule | read once in main, pass the value |
| Mutation of an argument | appending to a slice the caller owns | return a new value |
| I/O | writing a file inside the calculation | return what to write; let the shell write |
| Logging | log.Printf inside the rule | return the facts; log at the edge |
Timeline: an impure rule against a pure one.
Step Call Impure PriceWithTaxImpure(100) Pure PriceWithTax(100, 20)
1 t0 TaxPercent = 20 - -
2 t1 price(100) 120 120
3 t2 other code sets TaxPercent = 0 - -
4 t3 price(100) 100 (same call, new answer) 120Real scenarios: a discount rule that reads time.Now() and cannot be tested on Black Friday; a Laravel model accessor that calls now() and makes a snapshot test fail on the first of the month; a report function that mutates the slice it was given and corrupts the caller's data; a pricing function that reads a feature flag from the database.
Go and PHP:
// Package purity shows side effects, command-query separation, idempotence and
// immutability in the smallest examples that still compile and test.
package purity
import (
"fmt"
"time"
)
// TaxPercent is global state: any code can change it, so PriceWithTaxImpure
// does not return the same answer for the same argument.
var TaxPercent = 20
func PriceWithTaxImpure(net int) int { return net + net*TaxPercent/100 }
// PriceWithTax is pure: the output depends only on the arguments.
func PriceWithTax(net, taxPercent int) int { return net + net*taxPercent/100 }
// GreetingImpure reads the clock; a test cannot choose the answer.
func GreetingImpure() string { return Greeting(time.Now()) }
// Greeting is pure: the clock became an argument.
func Greeting(now time.Time) string {
if now.Hour() < 12 {
return "Good morning"
}
return "Good afternoon"
}
// Counter mixes a command and a query in Next: asking changes the answer.
type Counter struct{ n int }
func (c *Counter) Next() int { c.n++; return c.n }
// Tally separates them: Increment is a command (no result), Value a query (no change).
type Tally struct{ n int }
func (t *Tally) Increment() { t.n++ }
func (t Tally) Value() int { return t.n }
// Order status updates: SetStatus is idempotent, Append is not.
type Order struct {
Status string
Notes []string
}
// SetStatus can be retried safely: applying it twice equals applying it once.
func (o *Order) SetStatus(s string) { o.Status = s }
// AppendNote cannot: every retry adds another note.
func (o *Order) AppendNote(n string) { o.Notes = append(o.Notes, n) }
// AppendNoteOnce makes the operation idempotent with a caller-supplied key.
type Ledger struct {
seen map[string]bool
Notes []string
}
func (l *Ledger) AppendNoteOnce(key, note string) bool {
if l.seen[key] {
return false
}
if l.seen == nil {
l.seen = map[string]bool{}
}
l.seen[key] = true
l.Notes = append(l.Notes, note)
return true
}
// Cart is immutable: WithItem returns a new Cart and never touches the receiver.
type Cart struct{ items []string }
func (c Cart) WithItem(item string) Cart {
next := make([]string, len(c.items), len(c.items)+1)
copy(next, c.items)
return Cart{items: append(next, item)}
}
func (c Cart) Items() []string { return append([]string(nil), c.items...) }
func (c Cart) String() string { return fmt.Sprintf("Cart%v", c.items) }// Laravel: the pure rule takes the clock as an argument; the caller passes now().
final class TrialRule
{
public function isExpired(DateTimeImmutable $startedAt, DateTimeImmutable $now): bool
{
return $now >= $startedAt->modify('+14 days');
}
}
// controller or job: $rule->isExpired($user->trial_started_at->toImmutable(), now()->toImmutable())What purity buys: tests need no fakes (see TestPureAnswerDependsOnArguments), results can be cached (memoised) safely, calls can run in parallel without locks, and a bug has to be in the arguments or the body. What it costs: you pass more values around. That is the right price for rules and the wrong price for a logger, which is why the functional core and imperative shell puts the line in a specific place.
Command-query separation and idempotence Important
In plain words: a method should either do something or tell you something, not both; and an operation that might be retried should be safe to repeat.
Common misunderstanding: "CQS is the same as CQRS." Command-query separation is a method-level rule from Bertrand Meyer. CQRS is an architecture pattern that splits read models from write models; it grew from the idea but is a different decision (see Event Sourcing & CQRS for the architecture side). Fowler also notes exceptions to the rule: popping a stack both returns a value and changes state, and splitting it loses atomicity.
Definition: Fowler, crediting Meyer: queries "return a result and do not change the observable state of the system (are free of side effects)"; commands "change the state of a system but do not return a value". The payoff, in his words: "you can use queries in many situations with much more confidence, introducing them anywhere, changing their order." Idempotence is a different property: applying the operation twice has the same effect as applying it once. It is what makes retries safe.
| Operation | Command or query | Idempotent? | Why |
|---|---|---|---|
Tally.Value() | Query | Yes, and repeatable | Reads only |
Tally.Increment() | Command | No | Each call adds one |
Counter.Next() | Both (violation) | No | Asking changes the answer |
Order.SetStatus("paid") | Command | Yes | Setting the same value twice leaves the same state |
Order.AppendNote(n) | Command | No | A retry adds another note |
Ledger.AppendNoteOnce(key, n) | Command | Yes | The key makes the repeat a no-op |
HTTP PUT and DELETE | Command | Yes by HTTP semantics | |
HTTP POST | Command | No unless an idempotency key is used |
Timeline: a retry against a non-idempotent command.
Step Actor Action Stored notes
1 t0 client POST /orders/7/notes "paid by card" ["paid by card"]
2 t1 network response lost
3 t2 client retries the same request ["paid by card", "paid by card"]
4 t3 with key retries with Idempotency-Key: evt-1 ["paid by card"] (second call is a no-op)Real scenarios: a Go iterator Next() that advances and returns (Fowler prefers separate advance and current); Stripe-style idempotency keys on payment POSTs; a queue consumer processing the same message twice (at-least-once delivery); a Laravel job retried after a timeout; a migration that must be safe to run twice (CREATE TABLE IF NOT EXISTS).
The Go side is in the purity package above: Counter against Tally, SetStatus against AppendNote, and the keyed Ledger. For the messaging side see Idempotent Consumers & the Inbox Pattern and the HTTP side on API Idempotency.
// Laravel: idempotent write with a unique key; the second insert is a no-op.
DB::table('processed_events')->insertOrIgnore(['event_id' => $event->id, 'processed_at' => now()]);Immutability and value semantics Important
In plain words: if a value cannot change after it is created, nobody can change it behind your back.
Common misunderstanding: "In Go, passing a struct by value makes it immutable." It copies the struct header and fields, but a slice or map field still points at the caller's storage, so appending or writing through the copy can change the original. Immutability needs a copy of the contents (as Cart.WithItem does with make and copy) or an unexported field with no mutating methods.
Definition: an immutable value has no operation that changes it; "changes" return a new value. Go has no final, so immutability is a convention built from unexported fields, value receivers and defensive copies. The PHP 8.2 release page lists "readonly classes", so PHP 8.2 gives final readonly class (used by the lab's Quote) and DateTimeImmutable; Eloquent models are mutable by design, so keep them at the edge.
| Language feature | Helps with | Does not stop |
|---|---|---|
Go constants and const blocks | Fixed values and enum-like names | Anything that is not a constant expression |
| Go unexported fields plus value receivers | Callers mutating internals | Slices and maps shared by reference |
Go Items() returning a copy | Aliasing | Cost of the copy on huge slices |
PHP readonly properties and classes | Reassigning or initialising a property from outside; also indirect modification of a contained array (PHP raises Cannot indirectly modify readonly property, checked on PHP from the local install) | Mutating an object held inside (its own properties stay writable) |
PHP DateTimeImmutable | The classic DateTime::modify surprise |
Timeline of an aliasing bug:
Step Code items (caller) items (callee copy)
1 t0 a := []int{1, 2, 3} [1 2 3] -
2 t1 b := a (slice header copy) [1 2 3] [1 2 3] same backing array
3 t2 b[0] = 99 [99 2 3] (surprise) [99 2 3]
4 t3 b := append([]int(nil), a...) (copy) [99 2 3] [99 2 3] independent from now onReal scenarios: a Cart mutated by a pricing function and then charged the wrong amount; a PHP DateTime passed to a method that calls ->modify('+1 day') and moves the caller's date; a Go map returned from a getter and modified by a caller. The TestImmutableCart test in the purity package proves the copy behaviour.
Functional core, imperative shell Must-know
In plain words: put all decisions in pure code that takes values and returns values, and keep the code that touches the world (HTTP, database, clock, mail) thin and dumb around it.
Common misunderstanding: "This means writing everything in a functional language." It is an arrangement of ordinary code. Gary Bernhardt's screencast that named it describes "a Twitter client whose core is functional ... This functional core is surrounded by a shell of imperative code: it manipulates stdin, stdout, the database, and the network, all based on values produced by the functional core." Go and PHP can do it with plain structs and functions.
Definition: the functional core is the set of pure functions that decide; the imperative shell reads inputs, calls the core and performs the effects it asks for. The shell is tested with a few fakes or integration tests; the core is tested with plain values, exhaustively.
Timeline of one request through the pattern (the lab's Service.PlaceQuote):
Step Layer What happens Needs a fake?
1 shell read the request body and the clock no (edge)
2 shell call Order.Quote(now) -
3 core validate, subtotal, discounts, shipping, tax no (pure)
4 shell compare total with LargeOrderThreshold -
5 shell call Notifier.LargeOrder(total) if above yes: one recording fake
6 shell write the response no (edge)Real scenarios: an invoice-reminder job (the core package: Plan decides, Run loads, sends and records); a Laravel action class that validates in a Form Request, calls a pure QuoteCalculator, then dispatches an event; a CLI that reads files, calls a pure Transform, writes the output.
// Package core is a functional core with an imperative shell: Plan decides,
// Run does. Plan is pure, so its tests need no fakes at all.
package core
import (
"context"
"fmt"
"time"
)
type Invoice struct {
ID string
DueDate time.Time
Paid bool
Reminded bool
}
type Reminder struct {
InvoiceID string
Overdue int // whole days overdue
}
// Plan is the functional core: values in, values out, no clock, no I/O.
func Plan(invoices []Invoice, now time.Time) []Reminder {
var out []Reminder
for _, inv := range invoices {
if inv.Paid || inv.Reminded || !now.After(inv.DueDate) {
continue
}
days := int(now.Sub(inv.DueDate) / (24 * time.Hour))
out = append(out, Reminder{InvoiceID: inv.ID, Overdue: days})
}
return out
}
// Store and Mailer are the edges the shell talks to.
type Store interface {
Unpaid(ctx context.Context) ([]Invoice, error)
MarkReminded(ctx context.Context, id string) error
}
type Mailer interface {
Send(ctx context.Context, r Reminder) error
}
// Run is the imperative shell: load, decide with Plan, act, record.
func Run(ctx context.Context, s Store, m Mailer, now time.Time) (int, error) {
invoices, err := s.Unpaid(ctx)
if err != nil {
return 0, fmt.Errorf("load unpaid invoices: %w", err)
}
sent := 0
for _, r := range Plan(invoices, now) {
if err := m.Send(ctx, r); err != nil {
return sent, fmt.Errorf("send reminder for %s: %w", r.InvoiceID, err)
}
if err := s.MarkReminded(ctx, r.InvoiceID); err != nil {
return sent, fmt.Errorf("mark %s reminded: %w", r.InvoiceID, err)
}
sent++
}
return sent, nil
}package after
import "time"
// Notifier is the small interface the shell needs; the caller decides how.
type Notifier interface {
LargeOrder(total Cents)
}
// Service is the imperative shell: it owns the clock and the side effect.
// Everything with a rule in it stays in Order.Quote.
type Service struct {
Now func() time.Time
Notifier Notifier
}
func (s Service) PlaceQuote(o Order) (Quote, error) {
q, err := o.Quote(s.Now())
if err != nil {
return Quote{}, err
}
if q.Total > LargeOrderThreshold {
s.Notifier.LargeOrder(q.Total)
}
return q, nil
}// Laravel: the controller is the shell, QuoteCalculator is the core (see the lab).
$quote = $calculator->quote(items: $items, tier: $tier, express: $express, now: now()->toImmutable(), /* ... */);
if ($quote->total > self::LARGE_ORDER_FROM) {
LargeOrderQuoted::dispatch($quote->total); // the side effect stays in the shell
}The limit of the idea. The core stays pure only if all the data it needs is loaded before it runs. A rule that must query the database while deciding (for example "is this email already taken?") needs either a pre-loaded value, a repository interface the core calls (which makes it not quite pure), or a constraint in the database. Pick the cheapest honest option and name it.
Error handling vs happy path: guard clauses, early return, exceptions vs error values Must-know
In plain words: deal with everything that can go wrong first, at the top, and return; what is left is the real work, running straight down the page.
Common misunderstanding: "One return per function is cleaner." The single-exit rule comes from languages without cleanup (defer, finally, RAII). In Go and PHP early returns are the idiom. Effective Go: "The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise." Go Code Review Comments (Indent Error Flow): "Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first."
Definition: a guard clause is an early if that rejects an invalid state and returns (or throws). Early return is the technique. Two error models:
| Model | Go | PHP and Laravel |
|---|---|---|
| Error values | Functions return error; callers check if err != nil; wrap with fmt.Errorf("...: %w", err) (Go 1.13), combine with errors.Join (Go 1.20), test with errors.Is and errors.As; "Errors are values" (Go blog), so they can be programmed | Rare; used for result objects in some domains |
| Exceptions | panic and recover exist but are for programmer errors and package-internal control flow; Code Review Comments: "Do not discard errors using _ variables. If a function returns an error, check it" | Idiomatic: throw domain exceptions, catch at the edge; Laravel's exception handler renders them (render and report); Form Requests throw a validation exception for you |
Timeline of nested against guarded (the same Ship function; see the diagram and the snippet):
Step Nested Guarded
1 t0 if !cancelled { if cancelled { return ErrCancelled }
2 t1 if paid { if !paid { return ErrNotPaid }
3 t2 if items > 0 { if items <= 0 { return ErrEmpty }
4 t3 if !shipped { if shipped { return ErrShipped }
5 t4 ship() // depth 4 ship() // depth 0// Package guard compares nested conditionals with guard clauses and shows
// error values that callers can test with errors.Is.
package guard
import (
"errors"
"fmt"
)
type Order struct {
ID string
Paid bool
Items int
Shipped bool
Cancelled bool
}
var (
ErrCancelled = errors.New("order is cancelled")
ErrNotPaid = errors.New("order is not paid")
ErrEmpty = errors.New("order has no items")
ErrShipped = errors.New("order already shipped")
)
// ShipNested keeps the happy path at the deepest indentation.
func ShipNested(o *Order) error {
if !o.Cancelled {
if o.Paid {
if o.Items > 0 {
if !o.Shipped {
o.Shipped = true
return nil
} else {
return ErrShipped
}
} else {
return ErrEmpty
}
} else {
return ErrNotPaid
}
} else {
return ErrCancelled
}
}
// Ship handles each failure first and lets the success path run down the page.
func Ship(o *Order) error {
if o.Cancelled {
return ErrCancelled
}
if !o.Paid {
return ErrNotPaid
}
if o.Items <= 0 {
return ErrEmpty
}
if o.Shipped {
return ErrShipped
}
o.Shipped = true
return nil
}
// ShipAll wraps each failure with the order id; callers still match with errors.Is.
func ShipAll(orders []*Order) error {
var errs []error
for _, o := range orders {
if err := Ship(o); err != nil {
errs = append(errs, fmt.Errorf("ship %s: %w", o.ID, err))
}
}
return errors.Join(errs...)
}Real scenarios: a PHP method with five nested if levels around a database write; a Go handler that swallows err with _; an else after a return (Effective Go: when the if body ends in return, the else is dropped). A Laravel controller using abort_unless($order->isPaid(), 402) as a guard clause.
// Guard clauses in a Laravel action; the happy path is the last four lines.
public function handle(Order $order): void
{
abort_if($order->cancelled_at !== null, 409, 'Order is cancelled.');
abort_unless($order->isPaid(), 402, 'Order is not paid.');
abort_if($order->items->isEmpty(), 422, 'Order has no items.');
abort_if($order->shipped_at !== null, 409, 'Order already shipped.');
$order->forceFill(['shipped_at' => now()])->save();
ShipmentCreated::dispatch($order);
}Exceptions vs error values, the trade-off. Error values make every failure visible in the signature and every check explicit, at the cost of repetition (Rob Pike's "Errors are values" shows how to reduce it by programming errors, for example an error-tracking writer). Exceptions keep the happy path free of checks and let one handler deal with many failures, at the cost of invisible control flow. Neither is cleaner by itself: mixing them (a Go panic for a recoverable condition, a PHP exception used for ordinary branching) is what makes code hard to read.
Failure modes: guard clauses without defer leak resources in Go (open the file, then defer f.Close() immediately); too many returns hide the shape of the function; wrapping with %w at every layer produces a: b: c: d: not found messages nobody reads (Google's Go best practices: "avoid redundant information that the underlying error already provides").
Comments vs self-documenting code, and dead code Important
In plain words: let the code say what it does and use comments for why: the reason, the trap, the link to the spec.
Common misunderstanding: "Good code needs no comments." This is where the two big books disagree. Clean Code (Robert C. Martin), as Ousterhout quotes it from page 54: "The proper use of comments is to compensate for our failure to express ourselves in code ... Comments are always failures." Ousterhout replies that this "stigmatizes writing comments" and that junior developers will conclude "the safest thing is to write no comments". Martin's answer in the same exchange is that the chapter begins with "Nothing can be quite so helpful as a well placed comment" and calls comments a necessary evil. Both agree that a comment which restates the code is noise. The page's position: no comment may restate the code; every public API gets a doc comment; every non-obvious decision gets a why.
| Comment type | Keep? | Example |
|---|---|---|
| Restates the code | Delete; rename instead | // loop over items above a for |
| Doc comment on a public name | Keep (Go: a full sentence starting with the name; see Go Code Review Comments, Comment Sentences) | // Quote prices an order. It is pure: ... |
| Why, not what | Keep | // Spec: ISO 4217 minor units, so 1999 means 19.99 |
| Warning or trap | Keep | // Not safe for concurrent use. |
| TODO with an owner or ticket | Keep, and track | // TODO(ORD-412): remove after the v1 API is gone |
| Commented-out code | Delete: version control remembers | // oldTotal := t * 1.2 |
| Apology for a bad name | Rename | // x is the discount |
Dead code is code that can never run or whose result nobody uses: an unreachable branch, an unused function, a feature flag that was fully rolled out two years ago, a parameter nobody reads. It costs reading time and misleads searches. Go's compiler already rejects unused imports and local variables; unused and unparam (golangci-lint) find unused functions, types and parameters; PHPStan finds always-false checks, dead else branches and unreachable code after return from level 4. Commented-out code is dead code with a comment on it.
// Before: the comment repeats the code and the number has no name.
// check if total is above 50000
if r > 50000 {
Notify("ops", "big order")
}
// After: the constant names the rule; the doc comment on it says why.
// LargeOrderThreshold is the total above which operations is told.
const LargeOrderThreshold = Cents(50000)Timeline of a lying comment:
Step Date Change Comment says Code does
1 v1 Jan threshold 50000, comment "orders over 500" correct correct
2 v2 Jun threshold changed to 75000 still "over 500" wrong
3 v3 Dec new dev trusts the comment, writes a test wrong wrongDRY, WET and the rule of three Must-know
In plain words: write each fact once. But two pieces of code that merely look alike are not one fact, and merging them too early costs more than the duplication did.
Common misunderstanding: "DRY means no repeated lines." The statement quoted on Wikipedia (secondary) is about knowledge: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." Two functions with the same four lines that change for different reasons (accounting versus a label printer) are two facts that happen to look alike today. Merging them couples teams and, as soon as one of them needs a variation, adds a flag.
Definition:
| Term | Meaning |
|---|---|
| DRY (Don't Repeat Yourself) | One authoritative representation of each piece of knowledge: a rule, a constant, a schema, a format |
| WET | The opposite, usually glossed "write everything twice" (also "we enjoy typing"); in practice a pejorative for code with copied rules |
| Duplication of knowledge | The same business rule in two places that must always agree: merge it |
| Duplication of shape | Two blocks that look alike but change for different reasons: leave them apart |
| Rule of three | "Three strikes and you refactor": two similar instances do not need refactoring; at the third, extract (popularised by Fowler, attributed to Don Roberts) |
| Wrong abstraction | A shared function bent by flags and conditionals to serve callers that diverged |
Timeline of a wrong abstraction (the dry package):
Step Change Result
1 v1 InvoiceLine and ShippingLabel both print an amount two 1-line functions
2 v2 "They look the same" -> FormatAmount(c) one shared function
3 v3 labels need brackets -> FormatAmount(c, forLabel bool) flag argument
4 v4 invoices need padding and currency -> forInvoice, withCurrency four flags, five branches
5 v5 a change for invoices breaks labels two owners, one function
6 v6 split again, keeping only Cents.String() shared the real shared fact, onceGo and PHP: the shared fact is how an amount is written (Cents.String), so that lives in one place; the two formats stay separate.
// Package dry contrasts duplication of knowledge (merge it) with duplication of
// shape (leave it until the rule of three says otherwise).
package dry
import "fmt"
// Cents is money in the smallest unit.
type Cents int64
// FormatAmount is the result of merging two look-alike functions too early.
// Every new caller adds a flag, and the branches now serve two different owners.
func FormatAmount(c Cents, forInvoice, forLabel, withCurrency bool) string {
s := fmt.Sprintf("%d.%02d", c/100, c%100)
if forInvoice {
if withCurrency {
s += " EUR"
}
return fmt.Sprintf("%12s", s)
}
if forLabel {
return "[" + s + "]"
}
return s
}
// String is the shared knowledge: how an amount of cents is written. One place.
func (c Cents) String() string { return fmt.Sprintf("%d.%02d", c/100, c%100) }
// InvoiceLine and ShippingLabel look alike today but change for different
// reasons (accounting rules versus label printer width), so they stay separate
// and share only the one fact that really is the same.
func InvoiceLine(c Cents) string { return fmt.Sprintf("%12s", c.String()+" EUR") }
func ShippingLabel(c Cents) string { return "[" + c.String() + "]" }// Duplication of knowledge: the same tax rule in two classes. Merge it.
// Before: Invoice::tax() { return intdiv($net * 20, 100); } and Cart::tax() { return intdiv($net * 20, 100); }
// After: one constant and one method.
final class Tax
{
public const PERCENT = 20;
public static function on(int $netCents): int
{
return intdiv($netCents * self::PERCENT, 100);
}
}Real scenarios of knowledge duplicated: the free-shipping threshold in the cart, the invoice and the email; a validation rule in JavaScript and in a Form Request (generate one from the other or test them against the same cases); a status list in an enum, a CHECK constraint and a front-end dropdown; a database column default repeated in code.
Real scenarios of shape duplicated that should stay: two API handlers that both decode, validate and encode but for different resources; two table-driven tests with similar rows (Go's guidance for tests is readability over cleverness, see Clean tests); a service and its adapter that both map fields. Google's Go decisions page says code "can also be unnecessarily repetitive if the same or a similar code segment appears multiple times in close proximity", and the Go proverb says "A little copying is better than a little dependency": both sit in the same style guide because both are true.
What detects it: dupl (golangci-lint) finds duplicate fragments by token similarity, which flags shape, not knowledge; goconst finds repeated string and number literals, which flags some knowledge duplication; PHP has no equivalent in the sources saved for this chapter. A human decides which one it is, and that is the question in the diagram above.
YAGNI, KISS, speculative generality and premature abstraction Must-know
In plain words: build for today's requirement in the simplest way that is correct, and leave a clean seam, not a framework, for tomorrow's.
Common misunderstanding: "YAGNI means do not design." Fowler's bliki is explicit that it applies to presumptive features: "any code that supports a feature that isn't yet being made available for use". He names the costs even when the guess is right: the cost of build, the cost of delay (the value you could have shipped instead) and the cost of carry (the code has to be read and kept working). It does not forbid refactoring toward a flexible design later, and it assumes the tests and the refactoring habit that make later change cheap. Without those, YAGNI is just gambling.
Definition:
| Term | Meaning | Source |
|---|---|---|
| YAGNI | You Aren't Gonna Need It: do not build a capability you only presume you will need | XP; Fowler's bliki |
| KISS | Keep It Simple, Stupid: simplicity as a design goal | Associated with Kelly Johnson (Wikipedia, secondary) |
| Speculative generality | Hooks, interfaces, parameters and subclasses added "in case" and used by nobody; one of Fowler's smells, owned by Code Smells & Refactoring | smell catalogue |
| Premature abstraction | An abstraction created before there are two or three real cases to generalise from | rule of three |
| Least mechanism | Google's Go guide: "Sophisticated machinery often exists, but should not be employed without reason. It is easy to add complexity to code as needed, whereas it is much harder to remove existing complexity" | Go Style Guide |
| Clear is better than clever | The Go proverb | Go proverbs |
Timeline of a speculative interface:
Step Week Change Cost
1 w1 "We may add PayPal later" -> PaymentGateway interface 2 files, 1 mock
2 w2 Stripe implementation, bent to fit the interface a `Raw map` escape hatch added
3 w8 PayPal arrives with a redirect flow the interface does not fit; rewritten
4 w9 interface now has 14 methods, 9 of them no-ops for Stripe every change touches two typesThe seam, not the framework. YAGNI does not mean hard-code the database driver into the rule. Leave a small interface at the edge where a second implementation is already visible: the Notifier in the lab's after/service.go exists because the test needs a second implementation today. Google's Go best practices say to accept interfaces and return concrete types (GoTip #49), and the guide's least mechanism order is: a core language construct, then the standard library, then a dependency.
KISS is not "naive". The simplest thing that works includes the requirements you already know: money in integer cents, a clock you can control, an error you can test for. Leaving those out is not simple, it is a bug waiting.
Real scenarios: a repository interface with one implementation and a mock "for tests" in a language where the real thing is fast; a plugin system for a feature with one plugin; a BaseService class with four empty hooks; a Laravel package extracted from a three-line helper; microservices for a team of three.
Linters: unparam "reports unused function parameters" (a typical speculative argument); unused reports dead functions and types; PHPStan reports unused private methods and properties at its higher levels.
Boy scout rule Good to know
In plain words: when you touch a file, leave it a little cleaner than you found it: one better name, one extracted function, one deleted dead branch.
Common misunderstanding: "It licenses refactoring anything you pass." Small and local, in a separate commit (or a "preparatory refactoring" PR), with the tests green. A drive-by rewrite of a file you came to fix a typo in buries the real change and the review. Keep Fowler's two hats separate: add behaviour or refactor, not both in one commit (see Code Smells & Refactoring).
Definition: the boy scout rule is a team habit, usually phrased as "leave the campground cleaner than you found it"; this page does not attribute it to a specific book because no first-hand source was fetched. Its practical form: every change includes the cheapest improvement that makes the next change easier.
Timeline:
Step Commit Size Reviewer sees
1 c1 refactor: rename t -> subtotal in Quote 6 lines "nothing changed", merges in a minute
2 c2 fix: coupon expiry uses now() argument 9 lines the real fix, no noise
3 c3 chore: delete unused helper isOddPrice 12 lines a deletion, trivial to verifyWhere tooling helps: a lint "ratchet" that fails only on new issues (golangci-lint new-from-rev, PHPStan baselines) turns the boy scout rule into policy: old debt is allowed, new debt is not.
Framework at the edge, dependency direction, cohesion and coupling Important
In plain words: keep the rules of your business in code that does not import the web framework, the ORM or the vendor SDK; let the framework call your code, not the other way round.
Common misunderstanding: "Putting the framework at the edge means wrapping everything in interfaces." It means one thing: your pricing rule must be callable and testable without booting the framework. Eloquent models, Gin contexts and the Laravel Request can be everywhere in a small CRUD app and nowhere in a pricing engine.
Definition: dependency direction: source-code dependencies point from details (HTTP, database, vendor) toward policy (the rules). Robert C. Martin's dependency rule and the hexagonal architecture are on Clean, Hexagonal & Component Principles; the theory of cohesion (how strongly the parts of a module belong together) and coupling (how much modules know about each other) is on Design Quality. This page uses them as daily tests:
| Question | High cohesion looks like | Low cohesion looks like |
|---|---|---|
| What does the package name say? | pricing, ledger | utils, common, helpers |
| Do the functions use the same data? | They share types and invariants | They share a directory |
| Does one change touch one place? | A new tax rule edits pricing only | A new tax rule edits six packages |
| Question | Loose coupling looks like | Tight coupling looks like |
|---|---|---|
| Can you test the rule without a server? | Quote(now) with a struct | The rule calls request() and DB:: |
| Does the domain import the framework? | No | use Illuminate\Http\Request in the rule |
| What do modules exchange? | Plain values, small interfaces | Entire models and global state |
Go and Laravel in practice: in Go, the compiler forbids import cycles and internal/ stops outsiders from importing your internals, so layering errors show up early; in Laravel, controllers, Form Requests, jobs and event listeners are the edge, and plain classes under app/Orders (the lab uses QuoteCalculator, Tier, Quote) are the core. an architecture test can enforce "the domain namespace does not import Illuminate\Http".
Real scenario: a pricing rule inside a controller needs Request and Auth::user(); testing it needs a booted app and a database; changing the framework version re-tests the pricing rule. After the move, the rule needs a struct and a clock.
Deep modules and shallow modules Important
In plain words: a module is good when its interface is small and a lot happens behind it; it is bad when the interface is as big as the code it hides.
Common misunderstanding: "Smaller is always better." Ousterhout in the published exchange: "As methods get smaller and smaller there is less and less benefit to further subdivision. The amount of functionality hidden behind each interface drops, while the interfaces often become more complex. I call these interfaces 'shallow': they don't help much in terms of reducing what the programmer needs to know."
Definition: from A Philosophy of Software Design (John Ousterhout), through his site and the exchange. A deep module "replaces a large cognitive load (reading the detailed implementation) with a much smaller cognitive load (learning the interface)". A shallow module has an interface about as complex as its implementation. Entanglement ("conjoined" in his terms) is two methods that cannot be understood without reading each other: "If you've ever found yourself flipping back and forth between the implementations of two methods as you read code, that's a red flag". His fix: "Entangled methods can usually be improved by combining them so that all the code is in one place."
Timeline of over-decomposition:
Step Reader action What the reader learns
1 t0 reads ParseConfig() calls IsBlank, IsComment, ... names only
2 t1 jumps to IsBlank a one-line TrimSpace test
3 t2 jumps to IsComment must know IsBlank ran first
4 t3 jumps to SplitPair must know HasSeparator ran first
5 t4 returns to ParseConfig has re-assembled the parser in their head// Package deep contrasts a shallow decomposition with a deep module
// (John Ousterhout, A Philosophy of Software Design).
package deep
import (
"bufio"
"fmt"
"io"
"strings"
)
// The shallow version exports four tiny helpers. A caller must know the order
// to call them in and what each one assumes: the interface is as big as the
// implementation it hides.
func IsBlank(line string) bool { return strings.TrimSpace(line) == "" }
func IsComment(line string) bool { return strings.HasPrefix(strings.TrimSpace(line), "#") }
func HasSeparator(line string) bool { return strings.Contains(line, "=") }
func SplitPair(line string) (k, v string) {
k, v, _ = strings.Cut(line, "=")
return strings.TrimSpace(k), strings.TrimSpace(v)
}
// ParseConfig is the deep version: one function, one idea (key=value lines
// with comments), and the caller never learns how blank lines or comments are
// recognised. Errors carry the line number.
func ParseConfig(r io.Reader) (map[string]string, error) {
out := map[string]string{}
sc := bufio.NewScanner(r)
for n := 1; sc.Scan(); n++ {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("line %d: missing '=' in %q", n, line)
}
out[strings.TrimSpace(key)] = strings.TrimSpace(value)
}
return out, sc.Err()
}Where the two books actually differ, and where they agree:
| Topic | Clean Code (Robert C. Martin) | A Philosophy of Software Design (John Ousterhout) | Common ground |
|---|---|---|---|
| Function length | Very small; do one thing | Decompose until the interface is simple, not further | Modular design is good; over-decomposition is possible |
| Comments | "Comments are always failures" (as quoted) | Comments carry design information code cannot | A comment that restates the code is noise |
| Naming | Intention-revealing | Precise and consistent | Names matter a great deal |
| Interfaces | Small and focused | Narrow but deep | Hide what callers need not know |
The summary from the exchange itself: "We agree that it is possible to over-decompose, and that Clean Code 1st ed. doesn't provide much guidance on how to recognize over-decomposition." Use that sentence as your test: if you feel you are flipping between two functions to understand one idea, merge them.
Complexity metrics: cyclomatic, cognitive, and the tools Important
In plain words: complexity tools turn "this function feels hard" into a number you can track and a threshold you can enforce.
Common misunderstanding: "A low score means readable code." A score counts branches, not names, abstractions or comments. A function can score 3 and be unreadable; a flat switch can score 20 and be perfectly clear. Sonar's white paper makes the same point against cyclomatic complexity: two methods both score 4 and yet "it is intuitively obvious that the control flow of sumOfPrimes is more difficult to understand than that of getWords".
Definition:
| Metric | Computation | Strength | Weakness | Go tool | PHP tool |
|---|---|---|---|---|---|
| Cyclomatic complexity | gocyclo: "1 is the base complexity of a function, +1 for each 'if', 'for', 'case', '&&' or ' | '" | Number of independent paths, so a lower bound on test cases | A flat switch scores high; nesting is invisible | |
| Cognitive complexity | Sonar: ignore shorthand, add one for each break in linear flow, add more for nesting | Matches intuition: nesting costs more | Tool-specific details | gocognit | Sonar rules, PHPStorm and others |
| NPath complexity | Number of acyclic execution paths | Shows combinatorial explosion | Grows exponentially | none common | PHPMD NPathComplexity (200) |
| Function length | Lines and statements | Crude but cheap | Says nothing about structure | funlen (60 lines, 40 statements) | PHPMD ExcessiveMethodLength |
| Nesting depth | Nested if complexity | Targets the pyramid shape | nestif (5) | rule-specific | |
| Parameter count | Number of parameters | Targets long lists | none in the default set | PHPMD ExcessiveParameterList (10) |
Worked example with GetWords(number int) from the gocognit README, which reports the same function as cyclomatic 4 and cognitive 1 for the switch form (a switch counts once, not once per case). Counting the lab's before.Proc by hand with gocyclo's rules gives 15 (1 for the base, then one for each of 14 conditions); the clean after functions score at most 5 (subtotalOf: base, len, for, two ifs). Those are hand counts; the tools were not run (see the lab).
Line in the function cyclomatic cognitive (nesting adds)
1 func GetWords(number int) string { 1 0
2 switch number { 0 +1 (one for the whole switch)
3 case 1: return "one" +1 0
4 case 2: return "a couple" +1 0
5 case 3: return "a few" +1 0
6 default: return "lots" 0 0
7 } total 4 total 1Tooling facts, all from the saved docs: golangci-lint's reference lists gocyclo and gocognit with the comment "Default: 30 (but we recommend 10-20)", funlen with defaults of 60 lines and 40 statements, and nestif with a default of 5. PHPMD's codesize ruleset documents CyclomaticComplexity with reportLevel 10, NPathComplexity with 200 as "generally considered the point where measures should be taken", and ExcessiveParameterList with a minimum of 10. PHPStan has 11 levels (0 to 10, "0 is the loosest and 10 is the strictest", default 0) and Psalm has error levels 1 (strictest) to 8 (default 2); those are type checkers, not complexity metrics, but they are the other half of "the tool tells you before the reviewer does".
How to use the numbers: set the threshold slightly above today's worst function, fail CI on new violations, lower it as you refactor. A threshold of 10 on a codebase whose median is 25 gets disabled in a week.
Clean tests: FIRST principles, fast tests, independent tests, test readability Important
In plain words: tests are code that people read when something fails; they should be quick, self-contained and say what went wrong without opening the file.
Common misunderstanding: "Test code does not need to be clean." It is the code you read at the worst moment, red build, deadline. Go's Google decisions page: "It should be possible to diagnose a test's failure without reading the test's source."
Definition: the FIRST principles are a mnemonic from the Agile in a Flash series by Tim Ottinger and Jeff Langr (page saved as first-ottinger.txt): Fast, Independent, Repeatable, Self-validating, Timely.
| Letter | Meaning | Go habit | Laravel and PHP habit |
|---|---|---|---|
| Fast | Milliseconds, so people run them | pure functions need no setup; t.Parallel() | plain PHPUnit TestCase for pure classes, feature tests only where HTTP matters |
| Independent | No test depends on another or on order | each case owns its input; no shared package state | RefreshDatabase or DatabaseTransactions per test |
| Repeatable | Same result anywhere, any time | inject the clock; no network | Laravel's time helpers (travel), Http::fake, Queue::fake |
| Self-validating | Pass or fail, no human reads output | t.Errorf with got and want | assertions, not dd() |
| Timely | Written with or before the code | table test beside the function | PHPUnit test in the same PR |
Test readability. Failure messages name the function, the input, the actual result and the expected result. Go's convention is Slugify(%q) = %q, want %q; the lab's test follows it. Table-driven tests with a name field give every case a readable label under go test -run, and Google's Go guide asks for useful failure messages "detailing what caused the failure, what inputs resulted in an error, the actual result, what was expected".
// Package firsttest holds one function and a test written to the FIRST
// principles: fast, independent, repeatable, self-validating, timely.
package firsttest
import (
"strings"
"unicode"
)
// Slugify lower-cases s and joins its letter and digit runs with single dashes.
func Slugify(s string) string {
var b strings.Builder
dash := false
for _, r := range strings.ToLower(s) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
if dash && b.Len() > 0 {
b.WriteByte('-')
}
b.WriteRune(r)
dash = false
continue
}
dash = true
}
return b.String()
}package firsttest
import "testing"
// Fast: pure function, no I/O. Independent: each case owns its input.
// Repeatable: no clock, no network, no shared state. Self-validating: a plain
// comparison, no human reads output. Readable: the failure names input, got, want.
func TestSlugify(t *testing.T) {
t.Parallel()
tests := []struct {
name string
in string
want string
}{
{"spaces become one dash", "Clean Code Principles", "clean-code-principles"},
{"punctuation is dropped", "DRY, YAGNI & KISS!", "dry-yagni-kiss"},
{"leading and trailing noise is trimmed", " --Go-- ", "go"},
{"digits are kept", "Go 1.24 notes", "go-1-24-notes"},
{"empty stays empty", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := Slugify(tt.in); got != tt.want {
t.Errorf("Slugify(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}Timeline of a slow, dependent test suite:
Step Test Depends on Time
1 t1 TestCreateUser a real database 380 ms
2 t2 TestSendWelcome the user created by t1 120 ms (fails if t1 is skipped)
3 t3 TestExpiredCoupon the wall clock 50 ms (fails after midnight)
4 - whole suite order and shared state 4 min -> run once a day, ignoredThe test pyramid, doubles, TDD and flaky tests are on Testing Strategy & TDD; Go's mechanics (testing, -race, benchmarks, b.Loop) are on Testing & Benchmarking.
Per-language and per-tool behaviour
"Never name a rule without naming the tool." The same rule shows up differently in Go and in PHP, and some rules have no tool at all.
| Rule | Go: what enforces it | PHP and Laravel: what enforces it | No tool: a human must |
|---|---|---|---|
| Formatting | gofmt -l . (CI fails if it prints anything) | pint --test | Decide the SQL layout |
| Naming conventions | revive, Go Code Review Comments, go vet for some printf mistakes | PSR-12 and PER via Pint, PHPStorm inspections | Decide whether the name is honest |
| Unused code | compiler (unused imports and locals), unused, unparam | PHPStan (higher levels), PHPStorm | Decide whether a public function is really dead |
| Complexity | gocyclo, gocognit, cyclop, nestif, funlen | PHPMD CyclomaticComplexity, NPathComplexity, ExcessiveMethodLength | Decide whether a high score is a table, not a tangle |
| Duplication | dupl, goconst | no standard tool in the saved sources | Decide knowledge versus shape |
| Types and null safety | the compiler, go vet, staticcheck, nilnil | PHPStan (levels 0 to 10), Psalm (levels 8 to 1) | Decide what the type should be |
| Error handling | errcheck, errorlint, wrapcheck linters, go vet | PHPStan on @throws, Laravel handler | Decide who handles what |
| Side effects and purity | none directly; gochecknoglobals flags mutable package state | none directly | Keep the core pure by review |
| Architecture and dependency direction | import-cycle error in the compiler, internal/, depguard | a custom architecture test | Decide where the edge is |
| Tests | go test -race, t.Parallel, testing/synctest for time (not covered here) | PHPUnit, Laravel fakes | Decide whether a test reads well |
Linter names above come from the golangci-lint "Linters" page and reference config saved for this chapter; PHPMD names from its saved codesize page.
Naming conventions side by side:
| Concept | Go | PHP (PSR-1, PSR-12) | Laravel |
|---|---|---|---|
| Types and classes | OrderQuote (exported), orderQuote (package-private) | OrderQuote (StudlyCaps) | OrderQuote, models singular (Order) |
| Functions and methods | Quote, quote | quote() (camelCase) | quote() |
| Constants | MaxRetries (MixedCaps, no ALL_CAPS) | MAX_RETRIES | MAX_RETRIES, config keys snake_case |
| Packages and namespaces | pricing (lower case, single word) | App\Orders | App\Orders, Illuminate\... |
| Files | quote.go, quote_test.go | QuoteCalculator.php (PSR-4: file name equals class) | same |
| Tests | TestQuote, TestQuote_Expired (subtests with t.Run) | QuoteCalculatorTest, test_expired_coupon_is_ignored | same |
| Booleans | isPaid, hasItems (and no negatives such as notDisabled) | isPaid(), hasItems() | Eloquent: is_paid column, isPaid() accessor |
| Errors | ErrNotPaid (sentinel), *PaymentError (type) | PaymentFailedException | exceptions named for the failure |
Mechanics: how the tools work, and how to wire them
How gofmt works Important
gofmt parses a file into an abstract syntax tree and prints the tree back out with one fixed layout, so there are no options to argue about (tabs for indentation, alignment by column in comments and struct fields). It is idempotent: formatting formatted code changes nothing. The flags the docs list: -l print names of files whose formatting differs, -d print a diff, -w overwrite files, -s apply simplifications, -r 'pattern -> replacement' apply a rewrite rule to the source before formatting, -e print all errors. In CI use test -z "$(gofmt -l .)" (or golangci-lint fmt --diff), never -w.
# CI step: fail if any file is not gofmt-clean
test -z "$(gofmt -l .)" || { gofmt -d . ; exit 1; }How cyclomatic and cognitive complexity are counted Important
Cyclomatic: start at 1, add 1 for each decision point. Cognitive (Sonar's white paper): "A Cognitive Complexity score is assessed according to three basic rules: 1. Ignore structures that allow multiple statements to be readably shorthanded into one 2. Increment (add one) for each break in the linear flow of the code 3. Increment when flow-breaking structures are nested". The four kinds of increment are nesting, structural, fundamental and hybrid.
Code gocyclo gocognit
1 if a { +1 +1
2 if b { +1 +2 (nesting level 1)
3 for ... { +1 +3 (nesting level 2)
4 } else if c { +1 +1 (else-if: no nesting increment)
5 x := a && b +1 +1 (a sequence of the same operator counts once in cognitive)The else if and the boolean-operator rules in the last column follow the gocognit README's examples and the Sonar paper's "ignore shorthand" and "sequence of like operators" ideas; the exact edge cases are version-specific, so check the tool's README when a threshold decision depends on it.
Wiring it all into CI Must-know
A complete .golangci.yml for golangci-lint v2 (the format starts with version: "2"), enabling only what this chapter discusses:
version: "2"
linters:
default: standard # errcheck, govet, ineffassign, staticcheck, unused
enable:
- gocognit
- gocyclo
- funlen
- nestif
- dupl
- unparam
- revive
- errorlint
settings:
gocognit:
min-complexity: 15 # default 30, recommended 10 to 20
gocyclo:
min-complexity: 15
funlen:
lines: 60 # the default; keep or lower
statements: 40
ignore-comments: true
nestif:
min-complexity: 5
exclusions:
rules:
- path: _test\.go
linters: [funlen, dupl] # table tests are long and repetitive on purpose
formatters:
enable:
- gofmt
- goimports
issues:
new-from-rev: origin/main # the boy-scout ratchet: only new problems failThe default: standard line, the formatters: block and new-from-rev are all shown in the saved golangci-lint reference; the exact exclusions syntax should be checked against the version you install.
PHP side, three small files:
{ "preset": "laravel" }# phpstan.neon (PHPStan: 11 levels, 0 loosest and 10 strictest; start where the code passes)
parameters:
level: 6
paths: [app]
includes:
- phpstan-baseline.neon # existing errors; raise the level one step per PR<!-- phpmd.xml: size and complexity rules with explicit thresholds -->
<ruleset name="clean-code" xmlns="http://pmd.sf.net/ruleset/1.0.0">
<rule ref="rulesets/codesize.xml/CyclomaticComplexity">
<properties><property name="reportLevel" value="10"/></properties>
</rule>
<rule ref="rulesets/codesize.xml/ExcessiveParameterList">
<properties><property name="minimum" value="6"/></properties>
</rule>
</ruleset># CI for a Laravel app: style, types, tests (Psalm is the alternative to PHPStan)
./vendor/bin/pint --test
./vendor/bin/phpstan analyse --memory-limit=1G
./vendor/bin/phpmd app text phpmd.xml
php artisan test --parallelPre-commit hook (fast checks only, the slow ones stay in CI):
#!/bin/sh
# .git/hooks/pre-commit
test -z "$(gofmt -l .)" || { echo "gofmt needed"; exit 1; }
./vendor/bin/pint --test || exit 1The code review checklist
A review checklist is what a person does after the machines are green. Keep it short enough to use.
| # | Question | Rule behind it |
|---|---|---|
| 1 | Does every name say what and why? Would you find it by searching? | Naming |
| 2 | Does each function sit at one level of abstraction, and can you name it without "and"? | Small functions |
| 3 | Any flag, null or output argument? Any list of similar-typed arguments? | Arguments |
| 4 | Where are the side effects? Are they at the edge? | Pure functions, Functional core |
| 5 | Does any query method change state? Is every retried command idempotent? | CQS |
| 6 | Are failures handled first, with the happy path at the margin? Are errors wrapped with context, not duplicated text? | Error handling |
| 7 | Does every comment say why? Is there commented-out or dead code? | Comments |
| 8 | Is each duplicate one piece of knowledge, or just a similar shape? | DRY |
| 9 | Is there an interface, option or layer with exactly one user? | YAGNI |
| 10 | Does the rule import the framework? | Framework at the edge |
| 11 | If I split this, would I be flipping between two functions? | Deep modules |
| 12 | Do the tests fail with a message that names input, got and want? Are they fast and independent? | Clean tests |
| 13 | Is the diff one change, with refactors in a separate commit? | Boy scout rule |
Style, imports, formatting and unused code are not on the list: the tools own them.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| The 60-line handler | Split phases, pure core | Decode, call Quote, encode; the lab | Rules testable without HTTP | More files |
| The boolean parameter | Two named functions | RenderSummary, RenderDetail | Readable call sites | More names in the API |
| The long argument list | Option struct or named arguments | Config with zero-value defaults | Swap-proof, extensible | The struct can grow unrelated fields |
| The hidden clock | Pass now | Quote(now) | Deterministic tests | One more argument |
| The global hook | Inject a small interface | Notifier in Service | Testable, no patching | An interface to maintain |
| The pyramid of ifs | Guard clauses | Return at each failure | Flat code | Needs defer for cleanup |
| The helper everyone imports | Move it to the one caller, or name it for its domain | utils becomes pricing or money | Cohesion | Short-term churn |
| The abstraction nobody asked for | Delete it, inline it | Keep a seam only where a second implementation exists | Less to read | Rework if the guess was right |
| The wrong abstraction | Inline, then re-extract | Copy back into each caller and delete the flags | Each caller simple again | Temporary duplication |
| The comment that lies | Delete or rename | Replace by a named constant or function | One source of truth | Needs a test to be sure |
| The slow, dependent test | Pure core plus injected clock | Plan(invoices, now) | Milliseconds | Needs the design change first |
The fat handler and the fat controller
The lab shows both: the Go handler logic becomes Order.Quote(now) plus a Service, and the Laravel calc() becomes a Form Request, a pure QuoteCalculator and a thin invokable controller. For the full catalogue of moves see Code Smells & Refactoring.
The helper everyone imports
Step Action Check
1 1 list the callers of utils.FormatMoney (grep, gopls references) how many packages?
2 2 if one package: move it there and make it unexported compiler finds the rest
3 3 if several: create a package named for the concept (money) Cents.String() lives here
4 4 delete utils.FormatMoney in the same PR no dead copy leftThe wrong abstraction, step by step
Step Symptom Move
1 1 a shared function with 3 or more flags stop adding; list each caller's real path
2 2 callers pass literals that skip branches inline the function into each caller
3 3 delete the branches each caller does not use each copy is now small
4 4 look for the knowledge that is still identical extract only that (Cents.String)Choosing: which rule wins when two disagree
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| DRY against readability | Readability, unless it is the same knowledge | Rule of three | Duplicated shape is cheap; a wrong abstraction is expensive |
| Small functions against deep modules | Split until the interface gets simpler, not further | The "flipping back and forth" test | Ousterhout's red flag |
| Comments against self-documenting code | Names for what, comments for why | Doc comments on every public name | The two books agree on this much |
| YAGNI against "we know it is coming" | Build it when it is scheduled; leave a seam only if a second implementation exists | Make the later change cheap with tests | Fowler: the cost of carry and delay |
| Purity against convenience | Pure core, thin shell | Pass the clock and the config | Tests need no fakes |
| Early return against single exit | Early return | defer for cleanup | Effective Go and Code Review Comments |
| Exceptions against error values | The idiom of the language: values in Go, exceptions in Laravel | Wrap with context; handle at one edge | Mixing models is the real problem |
| Strict thresholds against a legacy codebase | Ratchet: fail only new violations | new-from-rev, PHPStan baseline | Old debt does not block delivery |
| A rule against a deadline | Ship; write the debt down; fix it in the next change | Boy scout rule | Cleanliness is a means to speed |
| Style preference against the formatter | The formatter | gofmt, Pint | The argument has no end otherwise |
A tie-breaker order, borrowed from Beck's four rules as Fowler lists them: passes the tests; reveals intention; no duplication; fewest elements. When two rules on this page collide, the one higher on that list wins.
In architecture: from a single process to a distributed system
Clean code rules are function-level, but they set up the architecture: a pure core can be moved into another process; a core that reads the clock and the database cannot.
Monolith: one process, one database
How it shows up: every rule applies at full strength; the compiler or PHPStan checks every refactor, and a rename is one commit.
Simplest correct usage: gofmt or Pint on save, a linter in CI, guard clauses, a pure pricing function, one test per rule.
Example (simple): a blog's PostController@store grows slug generation; extract Slugify, test it as a table (the lab's firsttest package) and move on.
Example (complex): the lab: a 52-line pricing function becomes a pure Order.Quote(now), with a recording notifier as the only fake.
Modular monolith and multiple databases
How it shows up: cohesion and coupling move up to modules. Each module exposes a small facade (a deep module); other modules call it with plain values; the rest is internal.
Rules: one vocabulary per module (what Order means in Billing differs from Shipping); no module reads another's tables; enforce imports with internal/ and depguard in Go, an architecture test in PHP.
Example: Billing needs the order total. It calls orders.Totals(ctx, id) (a query returning a value) and never reads the orders table. A command (orders.MarkInvoiced) is separate and idempotent.
Microservices: what survives across a network
What survives: pure functions move across a network unchanged; a core with no I/O can become a service or a library at will. What breaks: hidden dependencies (a global, a shared clock, a shared database) have to become explicit contracts, and a function name becomes an API.
| Rule | In a service | Across services |
|---|---|---|
| Command-query separation | Method level | HTTP GET is a query; POST is a command; CQRS at the architecture level |
| Idempotence | Keyed append | Idempotency keys on every retried POST; consumers deduplicate (see Idempotent Consumers & the Inbox Pattern) |
| Naming | One vocabulary per package | One vocabulary per bounded context; the same word can mean different things |
| DRY | One constant | Not across services: duplicating a small value object beats a shared library with a release cycle |
| Error values | error | Status codes, problem details, retry rules (see API Idempotency) |
Example flow: POST /orders (shell) calls Order.Quote(now) (core) and publishes OrderQuoted (side effect). A second service receives the event, deduplicates on event_id (idempotent), and runs its own pure Plan.
Distributed data: replicas, caches and shared schemas
Where it breaks: a "pure" rule that reads from a replica is only as repeatable as the replica's lag; a cached result of an impure function is a bug that appears at 03:00. Make the inputs explicit: pass the replica read's timestamp or version into the core, and cache pure functions by their arguments only.
Smells at this level: a shared database as an API (coupling through tables), a cached value whose format changed under old readers (version the key), a retry that is not idempotent on a replicated queue.
Scaling path: 1x, 10x, 100x
| Scale | Structure | Clean-code practice |
|---|---|---|
| 1x (one team, one app) | Monolith | Formatter and linter in CI, guard clauses, one pure core for the money rules |
| 10x (several teams, one repo) | Modular monolith | Module facades, depguard or an architecture test, complexity ratchet, review checklist |
| 100x (many teams, many services) | Services by capability | Per-service lint config in a shared template, contract tests, idempotency keys, a written vocabulary per bounded context |
Lab: clean a 52-line Go pricing function and a Laravel controller
You start from code that works and breaks half the rules on this page, pin its behaviour with a characterization test, then rewrite it step by step. The "after" Go code is compared with the "before" code inside the test suite, so a behaviour change cannot slip in. Nothing here needs Docker or a database.
Part A: Go
Setup. Run from the repository root; Go 1.24 or newer (the module declares go 1.24; this page was built with Go 1.27.4):
cd docs/snippets/design/clean-code-principles/go
gofmt -l . # prints nothing
go vet ./...
go test -race -count=1 ./...
# ok academy/clean-code-principles/after
# ok academy/clean-code-principles/args
# ok academy/clean-code-principles/before
# ok academy/clean-code-principles/core
# ok academy/clean-code-principles/deep
# ok academy/clean-code-principles/dry
# ok academy/clean-code-principles/firsttest
# ok academy/clean-code-principles/guard
# ok academy/clean-code-principles/purityThe starting point. before.Proc is shown in Small functions. List the problems before you read on: single-letter names (it, d, f, c, t, x, y, n, s, v, r), a flag argument (f), an output argument (res *int), a hidden clock (time.Now()), a package-level hook (Notify), pyramids of if, magic numbers (5000, 700, 1500, 50000), and comments that restate the code.
Step 1: the safety net. The characterization test pins current behaviour: seven priced cases, three invalid inputs and the notification. It describes what the code does, not what it should do.
package before
import (
"testing"
"time"
)
// A characterization test: it pins what the code does today, not what it should do.
func TestProcCharacterization(t *testing.T) {
future := time.Now().Add(time.Hour)
past := time.Now().Add(-time.Hour)
cases := []struct {
name string
items []Item
d string
f bool
c string
exp time.Time
want int
}{
{"plain below free shipping", []Item{{1000, 2}}, "", false, "", future, 2000 + 700 + 400},
{"gold gets 10 percent and free shipping", []Item{{1000, 2}}, "gold", false, "", future, 1800 + 0 + 360},
{"silver gets 5 percent", []Item{{3000, 2}}, "silver", false, "", future, 5700 + 0 + 1140},
{"express adds 1500 even for gold", []Item{{1000, 2}}, "gold", true, "", future, 1800 + 1500 + 360},
{"valid coupon takes 500 off", []Item{{3000, 1}}, "", false, "WELCOME", future, 2500 + 700 + 500},
{"expired coupon is ignored", []Item{{3000, 1}}, "", false, "WELCOME", past, 3000 + 700 + 600},
{"coupon needs a 2000 subtotal", []Item{{1500, 1}}, "", false, "WELCOME", future, 1500 + 700 + 300},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var got int
if err := Proc(tc.items, tc.d, tc.f, tc.c, tc.exp, &got); err != nil {
t.Fatalf("Proc returned %v", err)
}
if got != tc.want {
t.Errorf("Proc total = %d, want %d", got, tc.want)
}
})
}
}
func TestProcRejectsBadInput(t *testing.T) {
var out int
for name, items := range map[string][]Item{
"empty": nil,
"zero qty": {{100, 0}},
"neg price": {{-1, 1}},
} {
if err := Proc(items, "", false, "", time.Now(), &out); err == nil {
t.Errorf("%s: want an error, got nil", name)
}
}
}
func TestProcNotifiesOnBigOrders(t *testing.T) {
var calls int
Notify = func(to, msg string) { calls++ }
t.Cleanup(func() { Notify = nil })
var out int
if err := Proc([]Item{{100000, 1}}, "", false, "", time.Now(), &out); err != nil {
t.Fatal(err)
}
if calls != 1 {
t.Errorf("notify calls = %d, want 1", calls)
}
}Step 2: name things. Rename t to subtotal, d to tier, f to express, res away (step 5). Run the tests. This is the cheapest step and removes most of the comments.
Step 3: name the numbers. 5000, 700, 1500, 500, 2000, 10, 5, 20 and 50000 become constants with the rule in their name (freeShippingThreshold, expressSurcharge, LargeOrderThreshold). The notification threshold now has one definition.
Step 4: introduce types for the closed sets. d string becomes Tier, f bool becomes Speed (a flag argument turned into a named type), money becomes Cents. The coupon becomes a Coupon value whose zero value means "no coupon", so nobody passes nil or "".
Step 5: remove the output argument. Proc(..., res *int) error becomes Quote(now) (Quote, error): the result is returned, and the breakdown (subtotal, discount, shipping, tax, total) comes with it for free.
Step 6: make it pure. time.Now() becomes the now argument; the Notify global leaves the function entirely. What remains has no side effects.
Step 7: extract functions at one level of abstraction. subtotalOf, tierDiscount, couponDiscount, shippingFee, each with guard clauses. Quote reads as the pricing rule.
Step 8: put the side effect in a shell. Service.PlaceQuote owns the clock and the Notifier. This is the only code that needs a fake in a test.
The end state:
package after
import "fmt"
// Cents is an amount of money in the smallest currency unit.
type Cents int64
func (c Cents) String() string {
return fmt.Sprintf("%d.%02d", c/100, c%100)
}// Package after is the clean version of before: a pure core (Quote) that
// takes everything it needs as arguments and returns everything it computes.
package after
import (
"errors"
"time"
)
// Business rules live in named constants: one place per fact.
const (
goldDiscountPercent = 10
silverDiscountPercent = 5
taxPercent = 20
welcomeCouponCode = "WELCOME"
welcomeCouponOff = Cents(500)
welcomeCouponMinimum = Cents(2000)
standardShipping = Cents(700)
freeShippingThreshold = Cents(5000)
expressSurcharge = Cents(1500)
// LargeOrderThreshold is the total above which operations is told.
LargeOrderThreshold = Cents(50000)
)
var (
ErrNoItems = errors.New("order has no items")
ErrBadQuantity = errors.New("quantity must be positive")
ErrBadPrice = errors.New("unit price must not be negative")
)
type Tier string
const (
TierStandard Tier = ""
TierSilver Tier = "silver"
TierGold Tier = "gold"
)
type Speed int
const (
SpeedStandard Speed = iota
SpeedExpress
)
type LineItem struct {
UnitPrice Cents
Quantity int
}
// Coupon's zero value means "no coupon": callers never pass nil.
type Coupon struct {
Code string
ExpiresAt time.Time
}
type Order struct {
Items []LineItem
Tier Tier
Speed Speed
Coupon Coupon
}
type Quote struct {
Subtotal, Discount, Shipping, Tax, Total Cents
}
// Quote prices an order. It is pure: the clock arrives as an argument, nothing
// global is read or written, and the same arguments always give the same result.
func (o Order) Quote(now time.Time) (Quote, error) {
subtotal, err := subtotalOf(o.Items)
if err != nil {
return Quote{}, err
}
discount := tierDiscount(o.Tier, subtotal) + couponDiscount(o.Coupon, subtotal, now)
net := subtotal - discount
shipping := shippingFee(o.Tier, o.Speed, subtotal)
tax := net * taxPercent / 100
return Quote{
Subtotal: subtotal,
Discount: discount,
Shipping: shipping,
Tax: tax,
Total: net + shipping + tax,
}, nil
}
func subtotalOf(items []LineItem) (Cents, error) {
if len(items) == 0 {
return 0, ErrNoItems
}
var sum Cents
for _, it := range items {
if it.Quantity <= 0 {
return 0, ErrBadQuantity
}
if it.UnitPrice < 0 {
return 0, ErrBadPrice
}
sum += it.UnitPrice * Cents(it.Quantity)
}
return sum, nil
}
func tierDiscount(tier Tier, subtotal Cents) Cents {
switch tier {
case TierGold:
return subtotal * goldDiscountPercent / 100
case TierSilver:
return subtotal * silverDiscountPercent / 100
default:
return 0
}
}
func couponDiscount(c Coupon, subtotal Cents, now time.Time) Cents {
if c.Code != welcomeCouponCode {
return 0
}
if !now.Before(c.ExpiresAt) {
return 0
}
if subtotal < welcomeCouponMinimum {
return 0
}
return welcomeCouponOff
}
func shippingFee(tier Tier, speed Speed, subtotal Cents) Cents {
var fee Cents
if tier != TierGold && subtotal < freeShippingThreshold {
fee = standardShipping
}
if speed == SpeedExpress {
fee += expressSurcharge
}
return fee
}package after
import "time"
// Notifier is the small interface the shell needs; the caller decides how.
type Notifier interface {
LargeOrder(total Cents)
}
// Service is the imperative shell: it owns the clock and the side effect.
// Everything with a rule in it stays in Order.Quote.
type Service struct {
Now func() time.Time
Notifier Notifier
}
func (s Service) PlaceQuote(o Order) (Quote, error) {
q, err := o.Quote(s.Now())
if err != nil {
return Quote{}, err
}
if q.Total > LargeOrderThreshold {
s.Notifier.LargeOrder(q.Total)
}
return q, nil
}Step 9: prove nothing changed. TestParityWithBefore runs 72 combinations through both versions (3 tiers, 2 shipping speeds, 2 coupon states and 6 prices) and compares the totals:
package after_test
import (
"errors"
"testing"
"time"
"academy/clean-code-principles/after"
"academy/clean-code-principles/before"
)
var noon = time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
func TestQuoteTotals(t *testing.T) {
tests := []struct {
name string
order after.Order
want after.Cents
}{
{"plain below free shipping", after.Order{Items: items(1000, 2)}, 3100},
{"gold gets 10 percent and free shipping", after.Order{Items: items(1000, 2), Tier: after.TierGold}, 2160},
{"express adds a surcharge even for gold", after.Order{Items: items(1000, 2), Tier: after.TierGold, Speed: after.SpeedExpress}, 3660},
{"valid coupon takes 500 off", after.Order{Items: items(3000, 1), Coupon: coupon(noon.Add(time.Hour))}, 3700},
{"expired coupon is ignored", after.Order{Items: items(3000, 1), Coupon: coupon(noon.Add(-time.Hour))}, 4300},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.order.Quote(noon)
if err != nil {
t.Fatalf("Quote() error = %v", err)
}
if got.Total != tt.want {
t.Errorf("Quote().Total = %v, want %v", got.Total, tt.want)
}
})
}
}
func TestQuoteErrorsAreSentinels(t *testing.T) {
tests := []struct {
name string
items []after.LineItem
want error
}{
{"no items", nil, after.ErrNoItems},
{"zero quantity", []after.LineItem{{UnitPrice: 100, Quantity: 0}}, after.ErrBadQuantity},
{"negative price", []after.LineItem{{UnitPrice: -1, Quantity: 1}}, after.ErrBadPrice},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := after.Order{Items: tt.items}.Quote(noon)
if !errors.Is(err, tt.want) {
t.Errorf("Quote() error = %v, want %v", err, tt.want)
}
})
}
}
// The refactoring is safe only if the old behaviour survives: compare both versions.
func TestParityWithBefore(t *testing.T) {
exp := noon.Add(time.Hour)
for _, tier := range []string{"", "silver", "gold"} {
for _, express := range []bool{false, true} {
for _, code := range []string{"", "WELCOME"} {
for _, price := range []int{1, 999, 2000, 4999, 5000, 40000} {
var old int
if err := before.Proc([]before.Item{{P: price, Q: 1}}, tier, express, code, exp.Add(time.Hour*24*365*10), &old); err != nil {
t.Fatal(err)
}
o := after.Order{
Items: items(after.Cents(price), 1),
Tier: after.Tier(tier),
Coupon: after.Coupon{Code: code, ExpiresAt: exp.Add(time.Hour * 24 * 365 * 10)},
}
if express {
o.Speed = after.SpeedExpress
}
got, err := o.Quote(noon)
if err != nil {
t.Fatal(err)
}
if int(got.Total) != old {
t.Errorf("tier=%q express=%v code=%q price=%d: after=%d before=%d", tier, express, code, price, got.Total, old)
}
}
}
}
}
}
type recordingNotifier struct{ totals []after.Cents }
func (r *recordingNotifier) LargeOrder(total after.Cents) { r.totals = append(r.totals, total) }
func TestServiceNotifiesOnlyAboveTheThreshold(t *testing.T) {
n := &recordingNotifier{}
svc := after.Service{Now: func() time.Time { return noon }, Notifier: n}
if _, err := svc.PlaceQuote(after.Order{Items: items(1000, 1)}); err != nil {
t.Fatal(err)
}
if len(n.totals) != 0 {
t.Fatalf("small order notified: %v", n.totals)
}
if _, err := svc.PlaceQuote(after.Order{Items: items(100000, 1)}); err != nil {
t.Fatal(err)
}
if len(n.totals) != 1 {
t.Fatalf("large order notifications = %d, want 1", len(n.totals))
}
}
func TestCentsString(t *testing.T) {
if got, want := after.Cents(3105).String(), "31.05"; got != want {
t.Errorf("Cents(3105).String() = %q, want %q", got, want)
}
}
func items(price after.Cents, qty int) []after.LineItem {
return []after.LineItem{{UnitPrice: price, Quantity: qty}}
}
func coupon(expires time.Time) after.Coupon {
return after.Coupon{Code: "WELCOME", ExpiresAt: expires}
}Step 10: measure. Hand counts with the rules quoted under Complexity metrics; the tools were not run for this page (see below).
| Metric | Before (Proc) | After (Quote and helpers) |
|---|---|---|
| Longest function | 52 lines | 17 lines (Order.Quote) |
| Cyclomatic complexity (hand count) | 15 | at most 5 (subtotalOf) |
| Cognitive complexity (hand count, Sonar rules) | about 24 | at most about 6 |
| Package-level mutable variables | 1 (Notify) | 0 |
| Arguments of the main function | 6 (including an output pointer) | 1 (plus the receiver) |
| Hidden inputs | clock, global hook | none in Quote; both in Service |
| Copies of the large-order threshold | 1 literal | 1 constant |
| Needs a fake to test the rules | yes (global patch) | no (struct and clock) |
| Characterization and parity tests | pass | pass (72 combinations equal) |
Step 11 (optional, expected, not run): enforce it. Install the tools outside the module (go install github.com/fzipp/gocyclo/cmd/gocyclo@latest and go install github.com/uudashr/gocognit/cmd/gocognit@latest) and run:
gocyclo -over 10 ./before ./after
# expected: before/order.go ... Proc ... (15 by hand count) and nothing from ./after
gocognit -over 10 ./before ./after
# expected: Proc only
golangci-lint run --enable gocognit,gocyclo,funlen,nestif,unparam ./...
# expected: nestif and gocognit on before.Proc; nothing on afterPart B: Laravel
The same pricing rules in a Laravel 13 app on PHP 8.3 or newer. The PHP files were checked with php -l only; they were not run inside an application. Routes: Route::post('/quote', QuoteController::class) in routes/api.php.
The starting point. One method, calc, that reads everything from $request->all(), uses the clock helper now(), sends mail directly, takes a flag ($x) and returns a bare array shape:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class OrderController extends Controller
{
// computes the total
public function calc(Request $r, $x = false)
{
$d = $r->all();
$t = 0;
foreach ($d['items'] as $i) {
if ($i['q'] > 0) {
if ($i['p'] >= 0) {
$t += $i['p'] * $i['q'];
} else {
return response()->json(['error' => 'bad price'], 422);
}
} else {
return response()->json(['error' => 'bad qty'], 422);
}
}
$disc = 0;
if ($d['tier'] == 'gold') {
$disc = intdiv($t * 10, 100);
} elseif ($d['tier'] == 'silver') {
$disc = intdiv($t * 5, 100);
}
$c = 0;
if (($d['coupon'] ?? null) == 'WELCOME' && now()->lt($d['expires'])) {
if ($t >= 2000) {
$c = 500;
}
}
$n = $t - $disc - $c;
$s = 0;
if ($d['tier'] != 'gold' && $t < 5000) {
$s = 700;
}
if ($x) {
$s += 1500;
}
$res = $n + $s + intdiv($n * 20, 100);
if ($res > 50000) {
Mail::raw('big order', fn ($m) => $m->to('ops@example.test'));
}
return response()->json(['total' => $res]);
}
}Step 1: characterization tests against the controller using Laravel's HTTP tests ($this->postJson('/quote', ...)->assertJson(['total' => 3100])), with Laravel's time-travel test helpers for the coupon and Mail::fake() for the large order. Write them first and keep them green.
Step 2: a backed enum for the closed set replaces the string comparisons and carries the rule that belongs to it:
<?php
namespace App\Orders;
enum Tier: string
{
case Standard = '';
case Silver = 'silver';
case Gold = 'gold';
public function discountPercent(): int
{
return match ($this) {
self::Gold => 10,
self::Silver => 5,
self::Standard => 0,
};
}
public function shipsFree(): bool
{
return $this === self::Gold;
}
}Step 3: a readonly value object for the result (PHP 8.2 final readonly class):
<?php
namespace App\Orders;
/** A priced order. All amounts are integer cents. */
final readonly class Quote
{
public function __construct(
public int $subtotal,
public int $discount,
public int $shipping,
public int $tax,
public int $total,
) {}
}Step 4: the pure calculator. No facade, no now(), no mail; the clock is an argument and invalid input throws InvalidArgumentException. Named constants replace every literal:
<?php
namespace App\Orders;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* Pure pricing rules: no facade, no clock, no mail. The caller passes "now",
* so a unit test can choose the answer without booting the framework.
*/
final class QuoteCalculator
{
private const TAX_PERCENT = 20;
private const WELCOME_CODE = 'WELCOME';
private const WELCOME_OFF = 500;
private const WELCOME_MINIMUM = 2000;
private const STANDARD_SHIPPING = 700;
private const FREE_SHIPPING_FROM = 5000;
private const EXPRESS_SURCHARGE = 1500;
/**
* @param list<array{price: int, quantity: int}> $items
*/
public function quote(
array $items,
Tier $tier,
bool $express,
?string $couponCode,
DateTimeImmutable $couponExpiresAt,
DateTimeImmutable $now,
): Quote {
$subtotal = $this->subtotal($items);
$discount = intdiv($subtotal * $tier->discountPercent(), 100)
+ $this->couponDiscount($couponCode, $couponExpiresAt, $subtotal, $now);
$net = $subtotal - $discount;
$shipping = $this->shipping($tier, $express, $subtotal);
$tax = intdiv($net * self::TAX_PERCENT, 100);
return new Quote($subtotal, $discount, $shipping, $tax, $net + $shipping + $tax);
}
private function subtotal(array $items): int
{
if ($items === []) {
throw new InvalidArgumentException('Order has no items.');
}
$sum = 0;
foreach ($items as $item) {
if ($item['quantity'] <= 0) {
throw new InvalidArgumentException('Quantity must be positive.');
}
if ($item['price'] < 0) {
throw new InvalidArgumentException('Unit price must not be negative.');
}
$sum += $item['price'] * $item['quantity'];
}
return $sum;
}
private function couponDiscount(?string $code, DateTimeImmutable $expiresAt, int $subtotal, DateTimeImmutable $now): int
{
if ($code !== self::WELCOME_CODE) {
return 0;
}
if ($now >= $expiresAt) {
return 0;
}
if ($subtotal < self::WELCOME_MINIMUM) {
return 0;
}
return self::WELCOME_OFF;
}
private function shipping(Tier $tier, bool $express, int $subtotal): int
{
$fee = (! $tier->shipsFree() && $subtotal < self::FREE_SHIPPING_FROM) ? self::STANDARD_SHIPPING : 0;
return $express ? $fee + self::EXPRESS_SURCHARGE : $fee;
}
}Step 5: a plain PHPUnit test for it. It extends PHPUnit\Framework\TestCase, not the Laravel TestCase, because nothing needs the container, so it runs in milliseconds:
<?php
namespace Tests\Unit;
use App\Orders\QuoteCalculator;
use App\Orders\Tier;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
/** A plain PHPUnit TestCase: the calculator needs no container, so this is fast. */
class QuoteCalculatorTest extends TestCase
{
private const NOON = '2026-03-01 12:00:00';
public function test_plain_order_below_free_shipping(): void
{
$quote = $this->calculate([['price' => 1000, 'quantity' => 2]], Tier::Standard);
$this->assertSame(3100, $quote->total);
}
public function test_gold_gets_discount_and_free_shipping_but_pays_for_express(): void
{
$quote = $this->calculate([['price' => 1000, 'quantity' => 2]], Tier::Gold, express: true);
$this->assertSame(3660, $quote->total);
}
public function test_expired_coupon_is_ignored(): void
{
$quote = $this->calculate(
[['price' => 3000, 'quantity' => 1]],
Tier::Standard,
coupon: 'WELCOME',
expires: '2026-03-01 11:00:00',
);
$this->assertSame(4300, $quote->total);
}
public function test_empty_order_is_rejected(): void
{
$this->expectException(InvalidArgumentException::class);
$this->calculate([], Tier::Standard);
}
private function calculate(array $items, Tier $tier, bool $express = false, ?string $coupon = null, string $expires = '2026-03-01 13:00:00')
{
return (new QuoteCalculator)->quote(
$items,
$tier,
$express,
$coupon,
new DateTimeImmutable($expires),
new DateTimeImmutable(self::NOON),
);
}
}Step 6: validation at the edge. A Form Request validates the shape of the input so the calculator can assume it:
<?php
namespace App\Http\Requests;
use App\Orders\Tier;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
/** Input validation lives here, at the edge, not inside the pricing rules. */
class QuoteOrderRequest extends FormRequest
{
public function rules(): array
{
return [
'items' => ['required', 'array', 'min:1'],
'items.*.price' => ['required', 'integer', 'min:0'],
'items.*.quantity' => ['required', 'integer', 'min:1'],
'tier' => ['sometimes', Rule::enum(Tier::class)],
'express' => ['sometimes', 'boolean'],
'coupon' => ['nullable', 'string'],
'coupon_expires_at' => ['nullable', 'date'],
];
}
}Step 7: the thin controller and an event for the side effect. The invokable controller is the shell; the email is no longer sent inline, a listener can subscribe to LargeOrderQuoted (and the listener can be queued):
<?php
namespace App\Http\Controllers;
use App\Http\Requests\QuoteOrderRequest;
use App\Orders\LargeOrderQuoted;
use App\Orders\QuoteCalculator;
use App\Orders\Tier;
use DateTimeImmutable;
use Illuminate\Http\JsonResponse;
/** The imperative shell: read the request, call the core, publish the side effect. */
class QuoteController extends Controller
{
private const LARGE_ORDER_FROM = 50000;
public function __invoke(QuoteOrderRequest $request, QuoteCalculator $calculator): JsonResponse
{
$now = new DateTimeImmutable('now');
$quote = $calculator->quote(
items: $request->validated('items'),
tier: Tier::from($request->validated('tier', '')),
express: $request->boolean('express'),
couponCode: $request->validated('coupon'),
couponExpiresAt: new DateTimeImmutable($request->validated('coupon_expires_at') ?? '@0'),
now: $now,
);
if ($quote->total > self::LARGE_ORDER_FROM) {
LargeOrderQuoted::dispatch($quote->total);
}
return response()->json(['total' => $quote->total]);
}
}<?php
namespace App\Orders;
use Illuminate\Foundation\Events\Dispatchable;
final class LargeOrderQuoted
{
use Dispatchable;
public function __construct(public readonly int $total) {}
}Step 8: tools.
./vendor/bin/pint --test # style
./vendor/bin/phpstan analyse # types (start at the level the code passes)
./vendor/bin/phpmd app text phpmd.xml # complexity and argument count
php artisan test # the characterization tests from step 1
# all four: expected, not runHonest limits of this lab. The Go code is compiled, vetted and tested; the complexity numbers are hand counts; the PHP is syntax-checked only; and the after controller's Tier::from(...) would throw on an unknown tier, which the old code silently treated as standard. That is a behaviour change the characterization test would catch, and it belongs in its own commit.
Common misconceptions
| Belief | Reality |
|---|---|
| Clean code means short functions | It means functions at one level of abstraction with a simple interface; Ousterhout's red flag is flipping between two functions to understand one idea |
| DRY means no repeated lines | It means no repeated knowledge; similar code that changes for different reasons should stay apart |
| Comments are always a failure | Comments restating code are noise; comments explaining why, constraints and traps are design documentation (the two books agree on that much) |
| One return per function is cleaner | In Go and PHP, guard clauses and early return keep the happy path at the margin; use defer or finally for cleanup |
| YAGNI means no design | It means do not build presumptive features; keep the code easy to change with tests and refactoring |
| KISS means the naive solution | The simplest thing that meets the requirements you already know, including money in integers and a controllable clock |
| A formatter and a linter make code clean | They end style arguments and catch some smells; names, abstractions and boundaries are still judgement |
| Pure functions cannot do anything useful | Programs need effects; purity is about where the decisions are made (functional core, imperative shell) |
| Low cyclomatic complexity means readable | It counts paths, not names; a flat switch scores high and reads fine, a deeply nested function can score low |
| A Go struct passed by value is immutable | Slice and map fields still share storage; copy the contents or hide the field |
| An interface for every dependency is clean | One implementation and one mock is speculative generality; add the interface where a second implementation exists |
| Test code can be sloppy | It is read when something is broken; it should fail with input, got and want, and run fast and independently |
| CQS and CQRS are the same | CQS is a method-level rule; CQRS is an architecture pattern built on a similar idea |
| Refactor while fixing the bug, it saves time | Mixed commits bury the fix and make review and revert harder; do the boy scout step in its own commit |
Cheat sheet
| Topic | What to remember |
|---|---|
| Names | Intention-revealing, searchable, one word per concept; Go: short for small scopes, MixedCaps, no Get prefix; PHP: PSR-1 and PSR-12 |
| Formatting | gofmt -l . prints nothing; pint --test passes; never discuss spacing in review |
| Function shape | One level of abstraction, nameable without "and"; split by intention versus implementation, not by line count |
| Arguments | Zero-value defaults, option struct or named arguments; no flag, null or output arguments |
| Purity | Same arguments, same result, no side effects; the clock, config and randomness are arguments |
| Side effects | At the edge: functional core, imperative shell; the shell needs the fakes |
| CQS | Query returns and never changes; command changes and returns nothing (exceptions: pop, atomic operations) |
| Idempotence | Retried commands need a key or a set-style operation |
| Errors | Guard clauses first, happy path at the margin; wrap with %w, add context once; one error model per layer |
| Comments | Never restate the code; always say why; delete commented-out code |
| DRY | One fact, one place; merge knowledge, not shape; rule of three |
| YAGNI and KISS | Build what is needed now; keep a seam only where a second implementation exists |
| Deep modules | Narrow interface, much hidden; shallow micro-functions are a smell |
| Complexity | gocyclo and gocognit at 10 to 20 for new code, ratchet old code; PHPMD CyclomaticComplexity 10 |
| Tools | golangci-lint v2 with version: "2"; Pint and PHPStan (0 to 10) or Psalm (8 to 1) in CI |
| Tests | FIRST: fast, independent, repeatable, self-validating, timely; messages name input, got and want |
| Review | Use the 13-question checklist after the tools are green |
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 makes a function pure, and why does it matter for testing? Must-know
Answer
Answer: A pure function's result depends only on its arguments, and it has no side effects (no writes, no I/O, no clock, no globals). That gives referential transparency: a call can be replaced by its value. Tests need no fakes, results are cacheable and parallel-safe. In the lab, Order.Quote(now) is pure because the clock became an argument; see Pure functions.
2 — Explain functional core, imperative shell with an example. Must-know
Answer
Answer: Decisions live in pure functions that take values and return values; a thin shell reads inputs (request, clock, database), calls the core and performs the effects. In the lab Order.Quote is the core and Service.PlaceQuote is the shell that owns the clock and the Notifier. Only the shell needs a fake. See Functional core.
3 — When should you extract duplicated code? Must-know
Answer
Answer: When it is duplicated knowledge (the same rule that must always agree) and, as a guide, at the third occurrence (rule of three). Look-alike code that changes for different reasons should stay separate; merging it creates a wrong abstraction that grows flag arguments. The shared fact (how an amount is written) is extracted once, as in the dry package. See DRY.
4 — Why are flag arguments a smell, and what replaces them? Must-know
Answer
Answer: A boolean tells the function to do a different operation, and the call site (Render(r, true)) does not say which. Fowler: "My general reaction to flag arguments is to avoid them." Replace with two named functions (RenderSummary, RenderDetail), or a named type like Speed. See Arguments.
5 — Guard clauses or nested ifs, and what do Effective Go and Code Review Comments say? Must-know
Answer
Answer: Guard clauses. Effective Go says the code reads well "if the successful flow of control runs down the page, eliminating error cases as they arise", and Code Review Comments say to keep the normal path at minimal indentation and deal with errors first. Use defer so early returns do not leak resources. See Error handling vs happy path.
6 — What is command-query separation, and when do you break it? Important
Answer
Answer: Queries return a result and do not change observable state; commands change state and return nothing. It lets you call queries anywhere and in any order. Fowler's exceptions are operations whose atomicity matters, such as popping a stack or an atomic get-and-increment: splitting those is wrong. See CQS and idempotence.
7 — What is the difference between idempotent and pure? Important
Answer
Answer: Pure means deterministic (the result depends only on the arguments) and free of side effects. Idempotent is a separate property: applying an operation twice has the same effect as once (f(f(x)) = f(x)). A pure function need not be idempotent: x + 1 is pure and f(f(x)) differs from f(x). Idempotent commands can have side effects, like setting a status or inserting with a unique key, and they are what make retries safe.
8 — Cyclomatic and cognitive complexity: how do they differ and which tools measure them? Important
Answer
Answer: Cyclomatic counts independent paths (gocyclo: 1 plus each if, for, case, &&, ||); cognitive complexity (Sonar, gocognit) adds more for nesting and counts a switch once, so it tracks how hard code is to read. golangci-lint defaults to 30 for both and recommends 10 to 20; PHPMD reports CyclomaticComplexity at 10. See Complexity metrics.
9 — Where do Clean Code and A Philosophy of Software Design disagree? Important
Answer
Answer: On method length and comments. Martin favours very small functions and calls comments a failure to express oneself; Ousterhout argues that over-decomposition yields shallow, entangled methods and that comments carry design information code cannot. They agree that over-decomposition is possible and that comments restating code are noise. See Deep modules.
10 — What is YAGNI, and what does it not forbid? Important
Answer
Answer: Do not build presumptive features: the guess may be wrong, and even a right guess costs delay and carry. It does not forbid design, refactoring or leaving a small seam where a second implementation already exists, and it presumes tests that make later change cheap. See YAGNI and KISS.
11 — Which tools would you put in CI for a Go service and a Laravel app? Important
Answer
Answer: Go: gofmt -l . (must print nothing), go vet, golangci-lint v2 with gocognit, gocyclo, funlen, nestif, unparam, errorlint and a new-from-rev ratchet, plus go test -race. Laravel: pint --test, PHPStan (or Psalm) at a level the code passes with a baseline, PHPMD thresholds and php artisan test. See Wiring it all into CI.
12 — What do the FIRST principles ask of a test? Good to know
Answer
Answer: Fast, Independent, Repeatable, Self-validating, Timely. In practice: no network or clock, no shared state or order dependence, a plain comparison, and a failure message naming input, got and want, as Go's guidance asks. See Clean tests.
13 — Why is a Go struct passed by value not automatically immutable? Good to know
Answer
Answer: The copy duplicates the fields, but slice and map fields still point at the original storage, so writes through the copy are visible to the caller. Immutability needs defensive copies (as Cart.WithItem does) or hidden fields with no mutators. See Immutability.
Glossary
| Term | Meaning |
|---|---|
| Clean Code (Robert C. Martin) | A 2008 book on naming, small functions and comments (the Clean Code positions are taken from Ousterhout's quotations of it); quoted here only through pages that were read |
| A Philosophy of Software Design (John Ousterhout) | The book that argues for deep modules and for comments as design documentation; the counterweight to Clean Code |
| Naming | Choosing identifiers that state purpose; the cheapest and most valuable clean-code habit |
| Intention-revealing names | Names that say what a thing is for, not how it is implemented or what type it has |
| Searchable names | Names unique enough that a text search finds the concept and nothing else |
| Consistent vocabulary | One word for each concept across the codebase (not fetch, get and load for the same thing) |
| Formatting | The layout of source code; solved by a formatter, not by discussion |
| gofmt | Go's canonical formatter; flags -l (list), -d (diff), -w (write), -s (simplify), -r (rewrite rule) |
| Laravel Pint | An opinionated PHP code style fixer built on PHP CS Fixer, installed with new Laravel apps; presets laravel, per, psr12, symfony, empty |
| PSR-12 | The PHP-FIG extended coding style (4 spaces, LF, 120-character soft limit) |
| PER Coding Style | PHP-FIG's evolving coding style that "extends, expands and replaces PSR-12" |
| Small functions | Functions short enough to understand at a glance; the point is clarity, not a line count |
| One level of abstraction | Every statement in a function sits at the same conceptual height |
| Single responsibility at function level | A function has one reason to change; the small cousin of SRP |
| Arguments count | The number of parameters; many similar-typed ones are easy to swap |
| Flag arguments | A boolean parameter that selects between two behaviours; replace with two functions |
| Null arguments | Passing nil or null for "nothing"; prefer meaningful zero values or types |
| Output arguments | A parameter the function writes its result into; return the result instead |
| Option struct | A struct that collects arguments so call sites name them and zero values mean defaults |
| Pure functions | Functions whose result depends only on their arguments and which have no side effects |
| Side effects | Any observable change beyond the return value: writes, I/O, clock reads, mutation, logging |
| Referential transparency | A call can be replaced by its result without changing the program |
| Command-query separation | A method either changes state (command) or answers a question (query), not both; from Bertrand Meyer |
| CQRS | Command Query Responsibility Segregation: an architecture that separates read and write models; related to, but not the same as, CQS |
| Idempotence | Applying an operation twice has the same effect as applying it once |
| Idempotency key | A caller-supplied identifier that lets a server ignore a repeated command |
| Immutability | A value cannot change after creation; "changes" return a new value |
| Value semantics | Copying a value gives an independent value (careful with slices and maps in Go) |
| Functional core imperative shell | Pure decision code surrounded by a thin layer that performs I/O and effects |
| Error handling vs happy path | Handling failures first so that the successful flow reads straight down the page |
| Exceptions vs error values | Two error models: thrown and caught (PHP) versus returned and checked (Go); do not mix them in one layer |
| Early return | Returning as soon as the result or failure is known |
| Guard clauses | Early if statements that reject invalid states at the top of a function |
| Sentinel error | A package-level error value (ErrNotPaid) that callers compare with errors.Is |
| Comments vs self-documenting code | The debate about what code can say by itself and what only a comment can (the why) |
| Dead code | Code that never runs or whose results nobody uses, including commented-out code |
| Duplication | The same code, or the same knowledge, in more than one place; only the second kind must be merged |
| DRY | Don't Repeat Yourself: one authoritative representation of each piece of knowledge |
| WET | The opposite of DRY, "write everything twice" |
| Rule of three | Tolerate two similar instances; extract at the third |
| Wrong abstraction | A shared function bent by flags to serve callers that diverged |
| YAGNI | You Aren't Gonna Need It: do not build presumptive features |
| KISS | Keep It Simple, Stupid: simplicity as a design goal |
| Premature abstraction | An abstraction made before real cases exist to generalise from |
| Speculative generality | Hooks, interfaces or parameters added "in case"; one of Fowler's smells |
| Boy scout rule | Leave the code a little cleaner than you found it |
| Framework at the edge | Keeping controllers, ORM models and SDKs at the boundary so the rules do not import them |
| Dependency direction | Source dependencies point from details toward policy |
| Cohesion | How strongly the parts of a module belong together |
| Coupling | How much one module depends on another's details |
| Deep modules | Modules with a narrow interface that hide a lot of functionality |
| Shallow modules | Modules whose interface is nearly as complex as their implementation |
| Entanglement | Two methods that cannot be understood without reading each other |
| Cyclomatic complexity | The number of independent paths through a function: 1 plus each decision point |
| Cognitive complexity | Sonar's metric for understandability: increments for breaks in linear flow, more for nesting |
| NPath complexity | The number of acyclic execution paths through a method (PHPMD) |
| gocyclo | A Go tool that computes cyclomatic complexity; also a golangci-lint linter |
| gocognit | A Go tool that computes cognitive complexity; also a golangci-lint linter |
| golangci-lint | The Go linter runner; v2 config starts with version: "2" and has linters: and formatters: |
| funlen, nestif | golangci-lint linters for function length (60 lines, 40 statements) and nested ifs (5) |
| PHPMD | PHP Mess Detector: size and complexity rules such as CyclomaticComplexity and ExcessiveParameterList |
| PHPStan | A PHP static analyser with levels 0 (loosest) to 10 (strictest) |
| Psalm | A PHP static analyser with error levels 1 (strictest) to 8 (most lenient) |
| Code review checklist | A short list of human questions asked after the tools are green |
| FIRST principles | Fast, Independent, Repeatable, Self-validating, Timely: the properties of a good unit test |
| Fast tests | Tests that run in milliseconds so people run them |
| Independent tests | Tests that do not depend on each other or on execution order |
| Test readability | A failing test names its input, actual and expected values so it can be diagnosed without opening it |
| Characterization test | A test that pins what existing code does today, so a refactor can be proven safe |
| Go Code Review Comments | The Go wiki page of common review remarks (naming, error flow, receivers, comment sentences) |
| Effective Go | The Go project's guide to idiomatic code |
References
- Google, Go Style Guide (Clarity, Least mechanism), Style Decisions (Repetition, Useful test failures) and Best Practices (option structure, adding information to errors, accept interfaces and return concrete types)
- The Go Authors, Effective Go (names, formatting, control structures, errors) and Go Code Review Comments; Go Wiki: Test comments; Go Proverbs
- The Go Blog: gofmt, Errors are values, Working with errors in Go 1.13; release notes Go 1.13, Go 1.20 (
errors.Join), Go 1.24 (testing.T.Context,testing.B.Loop); gofmt source documentation; Go doc comments - golangci-lint: linters list and the reference configuration; gocyclo and gocognit READMEs
- PHP-FIG: PSR-12 and PER Coding Style; Laravel: Pint (and the 12.x page), Contribution guide: coding style, Testing
- PHPStan: rule levels and config reference; Psalm: error levels; PHPMD: codesize rules
- Martin Fowler, bliki: Function Length, Command Query Separation, Flag Argument, Beck Design Rules, Yagni, Code Smell
- John Ousterhout, A Philosophy of Software Design and the book page with the Second Edition notes; A Philosophy of Software Design vs Clean Code (the Ousterhout and Martin discussion)
- SonarSource, Cognitive Complexity: a new way of measuring understandability (white paper, version 1.7)
- Gary Bernhardt, Functional Core, Imperative Shell (Destroy All Software)
- Wikipedia (secondary): Don't repeat yourself, You aren't gonna need it, KISS principle, Command-query separation, Rule of three, Pure function, Referential transparency, Idempotence, Cyclomatic complexity