Skip to main content

Clean Code Principles

Learning objectives
  • Apply naming, function-size and abstraction-level rules to Go service code without fragmenting it into noise
  • Explain when duplication is cheaper than abstraction (DRY vs WET vs AHA) using a payments example
  • Write error handling that makes failure modes obvious to the next on-call engineer
  • Evaluate the cohesion and coupling of a package and argue for a better boundary
  • Map Go proverbs to classic clean-code principles in an interview discussion

TL;DR​

  • Code is read far more often than it is written. Optimize for the engineer debugging a failed transfer at 3 a.m., not for the author.
  • Names carry domain meaning and units: amountMinor, settledAt, ErrInsufficientFunds — never amt, t, err2. Better still, let types carry units (time.Duration, Money).
  • A function does one thing at one level of abstraction. In Go, prefer deep functions with simple interfaces over a swarm of three-line helpers.
  • Comments explain why (regulation, invariant, trade-off), never what the code already says.
  • DRY is about duplicated knowledge, not similar-looking code. Duplication is cheaper than the wrong abstraction — wait for the third case (AHA).
  • KISS and YAGNI apply to features, not to cheap-now/expensive-later decisions such as currency on money, idempotency keys and audit columns.
  • High cohesion, low coupling: group code by reason to change, talk through narrow interfaces, and do not reach through object graphs (Law of Demeter).

Why it matters​

In banking and e-commerce, unclear code is a correctness risk, not an aesthetic one. Many production incidents trace straight back to readability problems:

  • Unit confusion. A field named amount holds minor units (cents, đồng) in one service and major units in another. A refund of 100 becomes 100.00 instead of 1.00 — a 100× error that passes every type check.
  • Boolean traps. Transfer(ctx, from, to, amt, true, false) — is true "skip fraud check" or "allow overdraft"? The reviewer cannot tell, so the bug ships.
  • Swallowed errors. A PSP timeout is logged and ignored, the order is marked PAID although the card was never captured, and reconciliation finds it days later.
  • Audit and regulation. Auditors, incident reviewers and new joiners read your code. Explicit invariants and clear error paths are evidence of control; clever code is a finding.

Clean code lowers the cost of change, the quality attribute that dominates a system's lifetime cost (see Quality Attributes). As an architect you set the standards that make fifty engineers produce code that reads as if one team wrote it.

Core concepts​

Naming​

Good names are the cheapest documentation you will ever write.

RuleBadBetter
Reveal intentd, data, infodueDate, ledgerEntry
Encode units, or use typestimeout int, amount float64timeout time.Duration, amount money.Money
Use the domain's languageUpdateStatus(3)order.MarkShipped()
Avoid boolean flag parametersTransfer(a, b, m, true)TransferAllowingOverdraft(...) or an options struct
No stutter (Go)payment.PaymentServicepayment.Service
No Get prefix on getters (Go)acct.GetBalance()acct.Balance()
Initialisms keep one case (Go)OrderId, PspUrlOrderID, PSPURL

Go adds its own conventions. Name length is proportional to scope: i in a three-line loop is fine, a package-level variable named c is not. Receivers are one or two letters and consistent across methods (func (o *Order)). Package names are short lower-case nouns chosen so the call site reads well: ledger.Post(...), money.New(...), refund.Policy.

// Before: what does this compute? In what unit? What is f?
func calc(o *Order, f bool) float64 {
t := 0.0
for _, i := range o.Items {
t += i.P * float64(i.Q)
}
if f {
t = t * 0.98
}
return t
}

// After: names and types carry the domain; the flag became a concept.
func (o *Order) Subtotal() money.Money {
total := money.Zero(o.Currency)
for _, line := range o.Lines {
total = total.Add(line.UnitPrice.Times(line.Quantity))
}
return total
}

func ApplyLoyaltyDiscount(subtotal money.Money, tier LoyaltyTier) money.Money {
return subtotal.Sub(subtotal.BasisPoints(tier.DiscountBps()))
}

The "after" version also removed float64 from money — a primitive-obsession smell covered in Code Smells & Refactoring.

Small, focused functions​

"Do one thing" is a good smell detector: if you cannot describe a function without "and", it probably has two reasons to change. How far to take it is genuinely debated:

  • Clean Code (Martin) pushes for very small functions of a handful of lines.
  • A Philosophy of Software Design (Ousterhout) argues for deep modules: a simple interface hiding substantial implementation. Splitting a coherent 40-line function into eight 5-line functions that must all be read together makes the code shallower and harder to follow.

The Go community leans toward Ousterhout: a 40–60 line function that reads top to bottom is normal if it stays at one level of abstraction. Split mixed responsibilities, not line counts. Signals that a function really needs splitting:

  • It mixes I/O (HTTP, SQL, Kafka) with business rules.
  • It has more than about three levels of nesting.
  • It needs comments as section headers (// step 2: compute fees).
  • Testing one business rule requires a database or an HTTP server.
// Before: HTTP parsing, SQL, business rules (and, further down, PSP calls
// and e-mails) all live in one handler.
func (h *Handler) Refund(w http.ResponseWriter, r *http.Request) {
var req RefundRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
row := h.db.QueryRowContext(r.Context(),
`SELECT amount_minor, refunded_minor, status, captured_at
FROM payments WHERE id = $1`, req.PaymentID)
var amount, refunded int64
var status string
var capturedAt time.Time
if err := row.Scan(&amount, &refunded, &status, &capturedAt); err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
if status != "CAPTURED" || time.Since(capturedAt) > 180*24*time.Hour ||
refunded+req.AmountMinor > amount {
http.Error(w, "not refundable", http.StatusUnprocessableEntity)
return
}
// ... call PSP, update row, send e-mail, write response
}
// After: the rule lives on the domain type, is pure, and returns a
// specific error per reason. The handler only translates HTTP.
func (p *Payment) CheckRefundable(amount money.Money, now time.Time) error {
switch {
case p.Status != StatusCaptured:
return ErrNotCaptured
case now.Sub(p.CapturedAt) > refundWindow:
return ErrRefundWindowClosed
case p.Refunded.Add(amount).GreaterThan(p.Captured):
return ErrRefundExceedsCapture
}
return nil
}

The after version can be covered by a table-driven test with no database, and each rejection reason is now distinguishable in logs and API responses.

Levels of abstraction (the stepdown rule)​

A function should read like a paragraph written at one altitude. Mixing PlaceOrder-level intentions with strings.TrimSpace-level details forces the reader to change altitude every line. Arrange code so each function calls functions one level below it.

func (s *Service) PlaceOrder(ctx context.Context, cmd PlaceOrderCmd) (OrderID, error) {
cart, err := s.carts.Get(ctx, cmd.CartID)
if err != nil {
return "", fmt.Errorf("load cart %s: %w", cmd.CartID, err)
}
quote, err := s.pricing.Quote(ctx, cart)
if err != nil {
return "", fmt.Errorf("price cart: %w", err)
}
if err := s.inventory.Reserve(ctx, cart.Lines()); err != nil {
return "", fmt.Errorf("reserve stock: %w", err)
}
order := NewOrder(cart, quote)
if err := s.orders.Save(ctx, order); err != nil {
return "", fmt.Errorf("save order: %w", err)
}
return order.ID, nil
}

Every line is a business step; promotions, tax and SQL live one level down.

Comments: why, not what​

Code tells you what and how. Comments earn their place when they carry what code cannot: the reason, the constraint, the consequence.

KeepDelete
Why a non-obvious choice was made (regulation, contract, incident)Comments that restate the code
Invariants and preconditionsCommented-out code (git remembers)
Warnings about consequences ("changing this breaks settlement files")Change journals and author tags
Links to ADRs and ticketsSection dividers inside a long function (extract instead)
Doc comments on every exported identifierComments that have gone stale after a refactor
// Bad: restates the code.
// increment retry count
retries++

// Good: explains a constraint the reader cannot see.
// Our acquirer's contract only accepts reversals within 24h of the
// authorization; after that we must issue a refund (which carries fees).
// We stop retrying at 20h to leave margin for clock skew. See ADR-0042.
const maxReversalAge = 20 * time.Hour

Go doc comments start with the identifier's name, are full sentences, and describe the contract for callers: inputs, outputs, errors, idempotency, concurrency safety.

// Post records a balanced journal entry. It returns ErrUnbalanced if the
// debits and credits of entry do not sum to zero per currency. Post is
// idempotent on entry.ID: posting the same ID again returns the original
// result without writing. Post is safe for concurrent use.
func (l *Ledger) Post(ctx context.Context, entry JournalEntry) (PostingResult, error)

Error handling clarity​

In money systems the error path is the business logic: insufficient funds, frozen accounts, PSP timeouts and duplicate requests are daily events. Rules that keep error handling readable:

  1. Handle each error once. Either log it or return it, not both. Logging at every layer makes one failure appear four times and doubles alert noise.
  2. Add context as you return. fmt.Errorf("capture payment %s: %w", id, err) builds a readable chain: place order: capture payment pay_123: psp: context deadline exceeded.
  3. Make categories the caller acts on explicit. Domain rejection (422), not found (404), conflict (retry), transient infrastructure (retry with backoff), and unknown outcome (a PSP timeout: mark pending, reconcile — never retry blindly).
  4. Keep the happy path left-aligned. Guard clauses return early; the main flow is not nested inside else.
  5. No panics for business conditions. Panic is for programmer errors and impossible states.
  6. Never swallow silently. If you ignore an error deliberately (_ = tx.Rollback() after a failed commit), say why.
var (
ErrInsufficientFunds = errors.New("insufficient funds")
ErrAccountFrozen = errors.New("account frozen")
)

// UnknownOutcomeError means the PSP may or may not have charged the card.
// Callers must not retry with a new request; they must keep the payment
// PENDING and let status polling or reconciliation resolve it.
type UnknownOutcomeError struct {
PaymentID string
Cause error
}

func (e *UnknownOutcomeError) Error() string {
return fmt.Sprintf("payment %s: outcome unknown: %v", e.PaymentID, e.Cause)
}

func (e *UnknownOutcomeError) Unwrap() error { return e.Cause }

// httpStatus maps domain errors to HTTP at the edge, in one place.
func httpStatus(err error) int {
var unknown *UnknownOutcomeError
switch {
case errors.Is(err, ErrInsufficientFunds), errors.Is(err, ErrAccountFrozen):
return http.StatusUnprocessableEntity
case errors.As(err, &unknown):
return http.StatusAccepted // client polls GET /payments/{id}
default:
return http.StatusInternalServerError
}
}

Details of wrapping, errors.Is/errors.As and error types are on Error Handling; why "unknown outcome" must be a first-class state is on Idempotency & Exactly-Once.

DRY vs WET vs AHA​

  • DRY (The Pragmatic Programmer): every piece of knowledge has a single authoritative representation. The VAT rate, the rounding rule and the refund window must live in one place. Two loops that happen to look alike are not knowledge.
  • WET ("write everything twice"): tolerate duplication until the pattern is proven.
  • AHA ("avoid hasty abstractions", Kent C. Dodds), building on Sandi Metz's observation that duplication is far cheaper than the wrong abstraction.

A typical failure: card fees and bank-transfer fees look alike in month one, so someone writes calculateFee(method, amount, isInternational, isCorporate, isPromo). Six months later cards use interchange-plus pricing and transfers use flat tiers, and the shared function is a thicket of if method == ... branches that every change risks breaking for the other method.

// Shared KNOWLEDGE: how fees are rounded. One place.
func roundFee(m money.Money) money.Money { return m.RoundHalfEven() }

// Different knowledge that merely looks alike today: keep separate.
func CardFee(amount money.Money, card CardInfo) money.Money {
variable := amount.BasisPoints(cardRateBps(card))
return roundFee(variable.Add(fixedCardFee(card.Currency)))
}

func TransferFee(amount money.Money, kind TransferKind) money.Money {
return roundFee(transferTierFee(kind, amount))
}

The rule of three is a decent default: abstract on the third occurrence, when you can see what actually varies. Across microservices be even more cautious — a shared "common domain models" library couples release cycles of every service that imports it. Duplication across bounded contexts is usually correct.

KISS and YAGNI​

  • KISS — the simplest design that meets today's requirements. A switch over three payment methods is simpler than a plugin registry with reflection and config-driven loading.
  • YAGNI — do not build speculative features. No multi-tenant config engine for a single-tenant product; no generic workflow engine for one approval flow.

The nuance interviewers look for: YAGNI applies to reversible, cheap-to-add-later things. It does not excuse skipping decisions that are cheap now and very expensive later — "one-way doors". Currency on every money value, idempotency keys on mutating APIs, created_at/updated_by audit columns, and a stable public ID separate from the database key all cost almost nothing on day one and a painful migration on day 500.

Law of Demeter​

"Talk only to your immediate friends." A method should call methods on itself, its parameters, objects it creates, and its direct fields — not on objects returned by those.

// Before: checkout knows how customers, wallets and balances are structured,
// and the no-negative-balance rule is re-implemented at every call site.
if order.Customer().Wallet().Balance().Amount >= order.Total().Amount {
order.Customer().Wallet().Debit(order.Total())
}

// After: tell the owner of the data to do the work; the invariant lives
// in one place.
if err := wallet.Pay(order.Total()); err != nil {
return fmt.Errorf("pay order %s: %w", order.ID, err)
}

The law targets objects with behavior. Navigating plain data — a decoded JSON request req.Shipping.Address.City or a DTO — is fine; there is no encapsulation to break.

Cohesion and coupling​

  • Cohesion: how strongly the parts of a module belong together. The best is functional cohesion — everything serves one purpose (refund, ledger). The worst is coincidental — utils, common, helpers.
  • Coupling: how much one module must know about another. Roughly from worst to best: content (reaching into internals, or two services sharing tables), common (global mutable state), control (flag parameters that steer the callee), stamp (passing a whole struct when one field is needed), data (passing exactly what is needed).

In Go, package by feature usually beats package by layer: a change to refunds touches refund/ instead of handlers/, services/, models/ and repositories/ at once.

The same reasoning scales up: two microservices sharing a database table is content coupling at the architecture level (see Microservices Patterns).

Go proverbs mapped to principles​

Go proverbPrincipleIn payment and order code
"Clear is better than clever."KISS, readabilitySpell out rounding; no bit tricks or one-line ternary emulation
"A little copying is better than a little dependency."AHA, low couplingCopy a 10-line helper rather than import a "common" module with 40 transitive dependencies
"The bigger the interface, the weaker the abstraction."ISP, cohesionRefunder with one method beats PaymentGateway with fourteen
"Make the zero value useful."SimplicityGreat for sync.Mutex; but a zero Money with no currency should be invalid, so validate in constructors
"Errors are values."Clear error handlingTyped errors, wrapping, aggregation — program with errors, do not just check them
"Don't just check errors, handle them gracefully."Error handling clarityAdd context, decide retry vs fail vs pending
"interface{} says nothing."Intention-revealing typesA RefundRequested struct, not map[string]any
"Documentation is for users."Comments describe contractsDoc comments state idempotency and error semantics
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite."Standards via automationLet tools settle formatting so review focuses on design

Trade-offs​

OptionStrengthsWeaknessesChoose when
Many tiny functionsEach is easy to name and unit testReader jumps between files; shallow modules; deep stack tracesPure logic with genuinely distinct, reusable steps
Fewer, deeper functionsReads top to bottom; simple API hides complexityCan drift into a long function if uncheckedUse-case orchestration; most Go service code
DRY earlyOne place to change a ruleWrong abstraction accumulates flags and branchesThe duplicate is the same knowledge (VAT rate, rounding mode)
Tolerate duplication (WET/AHA)Copies evolve independentlyA bug fix may need to be applied twiceSimilar-looking code with different reasons to change; across bounded contexts
Comments explaining whyPreserve context code cannot expressCan rot if not maintainedRegulations, contracts, invariants, workarounds
Self-documenting code onlyNothing goes staleThe "why" is lostStraightforward logic with clear names

In practice​

  • Automate the mechanical rules. gofmt/goimports, and golangci-lint with revive (naming, doc comments), gocognit (cognitive complexity), errorlint (wrapping and comparison), dupl (copy-paste). Thresholds are team decisions; on legacy code, lint only new changes (new-from-rev) and ratchet. Details are in Code Review & Engineering Standards.
  • Keep a domain glossary. Authorization, capture, settlement, refund, chargeback, reversal are different things. A codebase that says charge, payment and txn for the same concept in three packages taxes every reader.
  • Questions in review are a signal. If a reviewer asks "what does this do?", the answer belongs in the code (a better name) or in a comment (the why), not only in the PR thread.

A worked "clean enough" example — a use-case function that reads top to bottom, names the domain, comments only the non-obvious, and wraps errors with context:

// Transfer moves money between two accounts. It is idempotent on
// cmd.IdempotencyKey: a retry with the same key returns the original
// transfer ID (backed by a unique index on transfers.idempotency_key).
func (s *TransferService) Transfer(ctx context.Context, cmd TransferCmd) (TransferID, error) {
if err := cmd.Validate(); err != nil {
return "", fmt.Errorf("invalid transfer: %w", err)
}

var id TransferID
err := s.uow.Do(ctx, func(tx Tx) error {
existing, found, err := tx.Transfers().ByIdempotencyKey(ctx, cmd.IdempotencyKey)
if err != nil {
return fmt.Errorf("check idempotency key: %w", err)
}
if found {
id = existing.ID
return nil
}

// LockPair locks both rows in account-ID order so that concurrent
// A->B and B->A transfers cannot deadlock.
from, to, err := tx.Accounts().LockPair(ctx, cmd.From, cmd.To)
if err != nil {
return fmt.Errorf("lock accounts: %w", err)
}

transfer, err := NewTransfer(from, to, cmd.Amount, cmd.IdempotencyKey)
if err != nil {
return err // domain error such as ErrInsufficientFunds; already descriptive
}
id = transfer.ID
return tx.Transfers().Save(ctx, transfer)
})
return id, err
}

The unit-of-work pattern behind s.uow.Do is explained in Design Patterns That Matter; the locking choice in Locking & Concurrency Control.

Common pitfalls​

  • amount with no unit or currency. Symptom: an occasional 100× overcharge or refund, found by customer complaints or reconciliation.
  • utils/common packages. They become dumping grounds every package imports; symptoms are import cycles and "who owns this?" questions.
  • Log-and-return. The same error appears at every layer; on-call engineers cannot tell one failure from four, and alert counts are inflated.
  • Over-fragmenting. Fifteen-frame stack traces for a simple flow; reviewers approve without understanding because the logic is spread across a dozen tiny functions.
  • Premature DRY across services. A shared models library forces lockstep deploys; one team's field rename breaks another team's build.
  • Stale comments. "Returns nil if not found" when it now returns ErrNotFound — the caller trusts the comment and dereferences nil.
  • Flag-parameter creep. Charge(ctx, p, true, false, true) — each new requirement adds a boolean instead of a concept.
  • Importing Java idioms. IPaymentService plus PaymentServiceImpl, getters and setters on every field — see SOLID in Go.

Interview angle​

  • Shows up as "What does clean code mean to you?", as a live code-review exercise ("review this handler"), or embedded in a design discussion ("how would you keep this codebase maintainable with 8 teams?").
  • A strong answer ties readability to cost of change and correctness, gives concrete heuristics (naming with units, one level of abstraction, error categories), acknowledges real debates (Martin vs Ousterhout on function size, DRY vs AHA), and explains how you scale standards: linters, templates, review guidelines, ADRs, golden-path repos.
  • Expected follow-ups: "When would you accept duplication?", "How do you propagate errors across layers in Go?", "How do you enforce this without slowing teams down?", "How do you clean up a legacy codebase you inherit?"
  • Red flags: dogma ("functions must be under five lines"), purely aesthetic arguments, no mention of tests or domain language, or applying Java-style ceremony to Go.

Self-check​

1. Why is DRY about knowledge rather than code? Give a payments example where merging similar code is wrong.

DRY means each business fact has one authoritative representation; duplicated facts drift apart and cause inconsistent behavior. Similar-looking code that encodes different facts should stay separate. Card fees and bank-transfer fees may share a shape today, but they change for different reasons (scheme pricing vs bank tariff), so merging them creates a flag-driven function where every change risks the other. The rounding rule, by contrast, is one fact and belongs in one place.

2. A 120-line ProcessPayment function lands in review. What do you check before asking for it to be split?
  • Does it mix levels or concerns: HTTP/SQL/PSP I/O interleaved with business rules?
  • Can the business rules be tested without infrastructure?
  • Is it nested deeply, or does it use comments as section headers?
  • Does it read top to bottom as a sequence of business steps?

If it is a linear orchestration at one level of abstraction, length alone is not a reason to split. If it mixes concerns, extract the pure rules and push I/O behind interfaces.

3. What must the doc comment of an exported Capture function state?

What it does in domain terms; the errors a caller should branch on (ErrNotAuthorized, ErrAlreadyCaptured, unknown outcome); whether it is idempotent and on what key; whether partial capture is allowed; and concurrency safety. It should not narrate the implementation.

4. When do you log an error, and when do you return it?

Return it (with added context) while some caller can still make a decision about it. Log it once at the boundary where it is finally handled — the HTTP handler, the consumer loop, the job runner — together with request and correlation IDs. Logging and returning creates duplicates. Exceptions: errors deliberately swallowed (best-effort cache writes) should be logged or counted at the point you swallow them.

5. Your team argues YAGNI against putting currency on the Money type because you only operate in one country. How do you respond?

YAGNI is for features that are cheap to add later. Currency on money is a one-way door: adding it later means migrating every table, event schema, API and cached value, while adding it now costs one field. Even single-market businesses meet other currencies (cross-border cards, FX settlement, marketplace sellers abroad). So: include currency now, but do not build FX conversion until it is needed.

6. order.Customer().Account().Limits().Daily appears in 30 call sites. What is wrong and how do you refactor it?

It violates the Law of Demeter: 30 callers depend on the internal structure of four types, so changing how limits are stored is shotgun surgery, and the limit-checking rule is probably re-implemented inconsistently. Move the behavior to the owner — e.g. account.CheckDailyLimit(amount) returning a domain error — and migrate call sites incrementally.

7. Explain cohesion and coupling using a Go package layout example.

Cohesion is how well a package's contents belong together; coupling is how much packages depend on each other's details. A utils package has low cohesion and creates coupling from everything to everything. A refund package containing the refund policy, its repository interface and its handler has high cohesion; it couples to payment only through a narrow interface. Package-by-feature generally raises cohesion and lowers coupling compared to package-by-layer.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Take the "before" refund handler above (or a real handler from your codebase) and clean it up in four commits:

  1. Rename everything to domain language with units or types (Money, time.Duration, typed IDs).
  2. Extract the refund rule into a pure method on Payment and cover it with a table-driven test: not captured, window closed, exceeds capture, partial refund allowed, exact full refund allowed.
  3. Define errors: one sentinel per rejection reason plus an unknown-outcome type for PSP timeouts, mapped to HTTP status in one function at the edge.
  4. Fix comments: delete every comment that restates code; add at least one "why" comment and a doc comment stating idempotency.

Done when: the rule tests run with no database or HTTP server, the handler is roughly 30 lines or fewer, golangci-lint run with revive and errorlint enabled is clean, and a teammate can explain the refund policy by reading only CheckRefundable.

Further reading​

  • Robert C. Martin, Clean Code (2008) — names, functions, comments, error handling. Read critically; some advice is Java-centric.
  • John Ousterhout, A Philosophy of Software Design, 2nd ed. (2021) — deep modules, information hiding, comments for what is not obvious.
  • Andrew Hunt and David Thomas, The Pragmatic Programmer, 20th anniversary ed. (2019) — DRY, orthogonality, tracer bullets.
  • Effective Go — naming, errors, interfaces.
  • Google Go Style Guide — style decisions and best practices, including naming and doc comments.
  • Go Code Review Comments — the community checklist of common review remarks.
  • Go Proverbs — Rob Pike, Gopherfest 2015.
  • Sandi Metz, "The Wrong Abstraction" (blog post, 2016).
  • Kent C. Dodds, "AHA Programming" (blog post).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).