Skip to main content

Code Smells & Refactoring

Learning objectives
  • Recognize the common code smells in Go backend code and name the refactoring that addresses each
  • Replace primitive money handling (float64) with a value type and explain the rounding and allocation rules
  • Refactor safely: characterization tests, small steps, separating refactoring from behavior change
  • Execute a multi-step refactor of a legacy checkout handler into a thin handler, a use case and adapters
  • Explain how refactoring scales to systems (parallel change, branch by abstraction, strangler fig)

TL;DR​

  • Refactoring is changing structure without changing observable behavior, in small, verifiable steps. If behavior changes, it is not refactoring — ship it separately and deliberately.
  • Smells are hints, not rules: long function, shotgun surgery, feature envy, primitive obsession, data clumps, repeated switch on type, speculative generality.
  • Money as float64 is the most expensive smell in this domain: int64(19.99*100) is 1998 in Go. Use integer minor units (or a decimal type) plus currency, with explicit rounding and allocation.
  • No tests, no refactoring. Pin legacy behavior with characterization tests first, including the bugs — then fix the bugs as separate, visible changes.
  • Make the change easy, then make the easy change (Kent Beck): preparatory refactoring right before a feature is the highest-value refactoring.
  • The same discipline scales to systems: parallel change for APIs and schemas, branch by abstraction for components, strangler fig for whole applications.

Why it matters​

Banks and e-commerce companies run on code that is years old, written under deadline, and carrying real money. You rarely get to rewrite it; you have to change it while it runs. Refactoring is how you keep the cost of change from rising every quarter — and in money systems it is also how you remove latent defects: a truncating cast in a fee calculation, a missing default that saves an order as paid without a charge, a retry path that charges twice.

Interviewers for architect roles probe this directly: "You inherit a 5,000-line payment module with no tests. What do you do?" The strong answer is a safe, incremental plan — not "rewrite it in microservices".

Core concepts​

Two hats​

Kent Beck's metaphor: at any moment you wear either the refactoring hat (structure changes, behavior identical, tests unchanged and green) or the feature hat (behavior changes, tests change). Never both in the same commit. In review, a PR that mixes a 400-line restructure with a rounding change hides the rounding change; a reviewer can approve the first only if it is provably behavior-neutral.

Code smells catalog​

SmellWhat you seeBank / e-commerce exampleTypical refactorings
Long functionScrolling, comment headers, deep nesting200-line checkout handler doing HTTP, SQL, pricing, PSP and e-mailExtract function, split phase
Large type (God object)Dozens of methods and dependenciesOrderManager used by every teamExtract type by actor, move method
Long parameter listFive or more parameters, several booleansTransfer(ctx, a, b, amt, cur, true, false, "")Introduce parameter object, replace flag with function
Primitive obsessionfloat64 amounts, string currencies and IDsRefund(orderID, paymentID string) swapped silentlyReplace primitive with value object, typed IDs
Data clumpsSame group of fields travels togetheramount, currency; bankCode, accountNo, holderNameIntroduce value object (Money, Beneficiary)
Repeated switch on typeSame switch provider in several packagesCharge, refund, webhook and reconciliation each switch on PSPReplace conditional with polymorphism (strategy)
Shotgun surgeryOne change edits many filesAdding a currency touches 14 filesMove function, combine into one module
Divergent changeOne file changes for many reasonspayments.go edited for fees, PSPs and reportingSplit by responsibility (SRP)
Feature envyFunction mostly uses another type's dataCheckout computing totals from cart internalsMove function to the data's owner
Message chainsa.B().C().D() navigationorder.Customer().Account().Limits().DailyHide delegate, tell-don't-ask
Speculative generalityHooks, params, interfaces nobody usesPlugin framework with one pluginInline, collapse hierarchy, delete
Temporary fieldField set only in some flowsOrder.retryToken valid only during captureExtract type for that flow
Comments as deodorantComment explains confusing code// careful: amount here is in cents unless...Rename, extract, introduce type
Ignored errors_ = or unchecked returnsrows.Scan errors dropped; zero balances returnedHandle or return with context

Primitive obsession: money as float64​

Binary floating point cannot represent most decimal fractions exactly. That is fine for physics and fatal for ledgers:

a, b := 0.1, 0.2
fmt.Println(a+b == 0.3) // false: a+b is 0.30000000000000004

price := 19.99
fmt.Println(int64(price * 100)) // 1998, not 1999: the cast truncates 1998.9999999999998

var total float64
for i := 0; i < 10; i++ {
total += 0.10
}
fmt.Println(total == 1.0) // false: 0.9999999999999999

A Go-specific trap: fmt.Println(0.1 + 0.2) with constants prints 0.3, because untyped constants use exact arithmetic. Your quick experiment passes; the same arithmetic on variables at runtime does not.

The refactoring is replace primitive with value object: integer minor units plus currency, with operations that refuse to mix currencies.

// Money is an amount in the currency's minor unit (cents for USD; VND has
// exponent 0 in ISO 4217, so its minor unit is the đồng itself).
// The zero value has no currency and is deliberately invalid.
type Money struct {
minor int64
currency Currency
}

func New(minor int64, cur Currency) (Money, error) {
if !cur.Valid() {
return Money{}, fmt.Errorf("invalid currency %q", cur)
}
return Money{minor: minor, currency: cur}, nil
}

func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, fmt.Errorf("%w: %s + %s", ErrCurrencyMismatch, m.currency, o.currency)
}
return Money{minor: m.minor + o.minor, currency: m.currency}, nil
}

// Allocate splits a non-negative amount by ratios, handing out the remainder
// one minor unit at a time so the parts always sum exactly to m.
// Splitting 100.00 three ways yields 33.34, 33.33, 33.33.
func (m Money) Allocate(ratios ...int64) ([]Money, error) {
var total int64
for _, r := range ratios {
if r < 0 {
return nil, errors.New("negative ratio")
}
total += r
}
if total == 0 || m.minor < 0 {
return nil, errors.New("allocate needs positive ratios and a non-negative amount")
}
parts := make([]Money, len(ratios))
var allocated int64
for i, r := range ratios {
share := m.minor * r / total
parts[i] = Money{minor: share, currency: m.currency}
allocated += share
}
for i := 0; allocated < m.minor; i++ {
parts[i%len(parts)].minor++
allocated++
}
return parts, nil
}

Design decisions to make explicitly, ideally in an ADR:

  • Representation. int64 minor units are fast and exact for amounts; a decimal library (for example shopspring/decimal or cockroachdb/apd) is better for FX rates, interest accrual and anything with more precision than the currency's minor unit. Many systems use both: decimal for intermediate computation, minor units for stored amounts.
  • Rounding mode and where it happens. Half-up vs half-even (banker's rounding), and per-line vs per-invoice tax rounding produce different totals. The rule usually comes from regulation, tax authority or contract — find out, then encode it in one place.
  • Allocation. Splitting a payment across sellers, installments or refunds must not create or destroy a cent. Allocate with remainder distribution guarantees that; it is also a perfect target for property-based tests.
  • Storage and wire format. BIGINT minor units or NUMERIC in the database, never FLOAT/DOUBLE; on the wire, integer minor units or decimal strings, never JSON floats. See Schema Patterns.

Data clumps and typed IDs​

Fields that always travel together want to be a type. amount and currency become Money; bankCode, accountNumber, holderName become Beneficiary; from and to dates become Period with a Contains method. Typed IDs fix a quieter bug class:

type OrderID string
type PaymentID string

// Before: Refund(ctx, paymentID, orderID string) — swap the arguments and
// it still compiles. After: the compiler rejects the swap.
func (s *Service) Refund(ctx context.Context, order OrderID, payment PaymentID, amount money.Money) error

Switch on type​

A single switch over a closed set is fine. The smell is the same switch repeated: switch provider in charge, refund, webhook parsing and reconciliation. Adding a PSP becomes shotgun surgery and one of the four places will be missed — often the one without a default case. Replace conditional with polymorphism: each provider becomes an adapter behind one interface (see Design Patterns), and the only remaining switch lives in the composition root.

Shotgun surgery vs divergent change​

They are mirror images. Shotgun surgery: one logical change, many files (adding a currency touches validation, formatting, fee tables, PDF templates, settlement export). Divergent change: one file, many unrelated reasons to change. The first says "pull related things together", the second says "split unrelated things apart". Both are cohesion problems (see Clean Code Principles).

Feature envy​

// Envy: checkout reaches into the cart's data to compute something the
// cart should know.
func (c *Checkout) itemsTotal(cart *Cart) (money.Money, error) {
total := money.Zero(cart.Currency)
for _, l := range cart.Lines {
var err error
if total, err = total.Add(l.UnitPrice.Times(l.Qty)); err != nil {
return money.Money{}, err
}
}
return total, nil
}

// Move function: the behavior now lives with the data it uses.
func (c *Cart) Subtotal() (money.Money, error)

Refactoring moves​

MoveFixesGo notes
Extract functionLong function, comment headersgopls offers "Extract function/variable" code actions
Inline function or variableNeedless indirection, speculative generalityDelete wrappers that only forward
RenameUnclear or inconsistent namesgopls rename updates every reference across packages
Introduce parameter objectLong parameter list, data clumpsA Cmd struct per use case
Replace primitive with value objectPrimitive obsessionMoney, typed IDs, time.Duration
Split phaseParse + compute + output tangledDecode into a typed command, then run pure logic
Move functionFeature envy, shotgun surgeryMove to the package that owns the data
Replace conditional with polymorphismRepeated switch on typeSmall interface plus registry built in main
Encapsulate fieldInvariants bypassedUnexported field, constructor, methods
Separate query from modifierFunctions that both read and mutateMakes retries and caching safe
Replace error code with errorbool/int status returnsSentinel or typed errors with errors.Is/As
Parallel change (expand/contract)Changing a public API or schemaAdd new, migrate callers, remove old
Branch by abstractionReplacing a large component in placeInterface in front, toggle between implementations
Strangler figReplacing a whole systemRoute traffic slice by slice to the new system

gofmt -r 'pattern -> replacement' handles simple mechanical rewrites across a codebase; for anything semantic, prefer gopls.

Refactoring safely​

  1. Characterization tests first. Michael Feathers' term for tests that capture what the code does today, not what it should do. For a handler: drive it with httptest, record responses and what the fakes received (amounts sent to the PSP, rows written), and assert on them. Golden files work well for large outputs such as settlement exports.
  2. Pin the bugs, too. If the current code truncates 19.99 to 1998, the characterization test asserts 1998 with a // BUG: comment. Fixing it later is a visible, reviewed behavior change.
  3. Small steps, always green. Each step compiles and passes tests; commit after each. If a step goes red and the fix is not obvious in a few minutes, revert and take a smaller step.
  4. Separate PRs for refactoring and behavior change. Reviewers can verify a pure refactor quickly; a behavior change gets the scrutiny it deserves.
  5. For money paths, compare in production. Run old and new calculations side by side (shadow mode), log mismatches, and switch over behind a feature flag only after a clean period. This catches inputs your tests never imagined.
  6. Respect contracts at boundaries. Exported Go APIs, HTTP/gRPC contracts, event schemas and database columns are consumed by others: use parallel change, not rename-in-place (see Zero-Downtime Schema Migrations).

Worked example: refactoring a checkout handler​

Step 0 — the original​

A realistic legacy handler. Read it once and count the problems before reading the list.

func (h *Handler) Checkout(w http.ResponseWriter, r *http.Request) {
var req map[string]interface{}
json.NewDecoder(r.Body).Decode(&req)

userID := req["user_id"].(string)
items := req["items"].([]interface{})
var total float64
for _, it := range items {
m := it.(map[string]interface{})
var price float64
h.db.QueryRow("SELECT price FROM products WHERE sku = '" + m["sku"].(string) + "'").Scan(&price)
total += price * m["qty"].(float64)
}

if c, ok := req["coupon"].(string); ok && c != "" {
var kind string
var value float64
h.db.QueryRow("SELECT kind, value FROM coupons WHERE code = $1", c).Scan(&kind, &value)
switch kind {
case "percent":
total = total - total*value/100
case "fixed":
total = total - value
}
}
if total < 0 {
total = 0
}

var chargeID string
var err error
switch req["provider"] {
case "stripe":
chargeID, err = h.stripe.Charge(int64(total*100), "usd", req["token"].(string))
case "paypal":
chargeID, err = h.paypal.Pay(fmt.Sprintf("%.2f", total), req["token"].(string))
}
if err != nil {
log.Println("charge failed", err)
w.WriteHeader(500)
return
}

var orderID int64
h.db.QueryRow("INSERT INTO orders (user_id, total, charge_id, status) VALUES ($1, $2, $3, 'PAID') RETURNING id",
userID, total, chargeID).Scan(&orderID)

go h.mailer.Send(userID, fmt.Sprintf("Thanks! Order %d total $%.2f", orderID, total))

w.Write([]byte(fmt.Sprintf(`{"order_id": %d, "total": %.2f}`, orderID, total)))
}

What is wrong, roughly in order of severity:

  1. Unknown provider charges nothing and saves the order as PAID. The switch has no default, so chargeID is empty and err is nil.
  2. SQL injection through string-concatenated sku.
  3. No idempotency. A client retry after a timeout charges the card again.
  4. Charge before the order exists. If the insert fails after a successful charge, the customer pays and there is no order.
  5. Ignored errors from Decode, Scan and the insert; unchecked type assertions panic on malformed input.
  6. Money as float64: int64(total*100) truncates; the currency is hard-coded; the fixed coupon ignores currency.
  7. Repeated switch on provider (refunds and webhooks have their own copies).
  8. N+1 queries for prices; fire-and-forget goroutine for e-mail (lost on crash, unbounded under load).
  9. Hand-built JSON and no Content-Type; every failure, including a card decline, becomes a bare 500.

Step 1 — pin current behavior​

Before touching anything, write characterization tests: a real Postgres via testcontainers (or the team's existing test DB) seeded with products and coupons, fakes for the Stripe and PayPal clients that record what they receive, and httptest to drive the handler.

func TestCheckout_Characterization(t *testing.T) {
tests := []struct {
name string
body string
wantStatus int
wantCharged int64 // minor units the fake Stripe client received
}{
{"single item no coupon", `{"user_id":"u1","items":[{"sku":"TSHIRT","qty":1}],"provider":"stripe","token":"tok"}`, 200, 1998}, // BUG: 19.99 truncated to 1998
{"percent coupon", `{"user_id":"u1","items":[{"sku":"TSHIRT","qty":2}],"coupon":"TEN","provider":"stripe","token":"tok"}`, 200, 3598},
{"unknown provider", `{"user_id":"u1","items":[{"sku":"TSHIRT","qty":1}],"provider":"momo","token":"tok"}`, 200, 0}, // BUG: order saved as PAID
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env := newCheckoutEnv(t) // seeded DB + recording fakes
rec := httptest.NewRecorder()
env.handler.Checkout(rec, httptest.NewRequest(http.MethodPost, "/checkout", strings.NewReader(tt.body)))

if rec.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d", rec.Code, tt.wantStatus)
}
if got := env.stripe.chargedMinor(); got != tt.wantCharged {
t.Errorf("charged = %d, want %d", got, tt.wantCharged)
}
})
}
}

The expected values were obtained by running the current code, not by reasoning about what is correct. That is the point. (3598 is what the float arithmetic currently produces for two shirts at 19.99 with 10% off: 35.982 truncated to cents.)

Step 2 — fix the dangerous bugs, as behavior changes​

These are not refactorings. Each is a small PR with its own test flipping from the BUG expectation to the correct one:

  • Add default: return 400 unsupported provider — the unknown-provider case now asserts no order is written.
  • Parameterize the sku query.
  • Check every error and replace unchecked type assertions with a typed request struct and validation.

Shipping these first reduces risk immediately, even if the rest of the refactor is paused.

Step 3 — split phase: decode into a typed command​

type checkoutRequest struct {
UserID string `json:"user_id"`
Items []requestItem `json:"items"`
Coupon string `json:"coupon,omitempty"`
Provider string `json:"provider"`
Token string `json:"token"`
}

type requestItem struct {
SKU string `json:"sku"`
Qty int64 `json:"qty"`
}

func (r checkoutRequest) toCommand(idemKey string) (order.PlaceOrderCmd, error) {
if r.UserID == "" || len(r.Items) == 0 || r.Token == "" {
return order.PlaceOrderCmd{}, ErrInvalidRequest
}
lines := make([]order.Line, 0, len(r.Items))
for _, it := range r.Items {
if it.Qty <= 0 {
return order.PlaceOrderCmd{}, fmt.Errorf("%w: qty for %s", ErrInvalidRequest, it.SKU)
}
lines = append(lines, order.Line{SKU: order.SKU(it.SKU), Qty: it.Qty})
}
return order.PlaceOrderCmd{
CustomerID: customer.ID(r.UserID),
Lines: lines,
CouponCode: r.Coupon,
Method: payment.MethodCode(r.Provider),
CardToken: r.Token,
IdempotencyKey: idemKey,
}, nil
}

Behavior is unchanged; characterization tests stay green.

Step 4 — replace the primitive: introduce Money​

Switching from float64 to Money changes results wherever truncation happened (1998 becomes 1999). That makes this step a behavior change disguised as a refactor, so treat it as one: agree the rounding rule with finance, flip the BUG expectations in the tests, ship it alone behind a flag if volumes are high, and check whether historical orders need a reconciliation note. Prices move from NUMERIC/FLOAT reads into money.Money at the repository boundary.

Step 5 — extract pricing into a pure function​

Pricing becomes a function with no I/O. Prices are batch-loaded (fixing the N+1) and passed in; the coupon becomes a value object whose Apply holds the one remaining switch over coupon kinds — a closed set, so a switch is fine.

// Quote prices the lines with the given prices and optional coupon.
// It is pure: same inputs, same output, no I/O.
func Quote(lines []order.Line, prices map[order.SKU]money.Money, coupon *Coupon) (money.Money, error) {
if len(lines) == 0 {
return money.Money{}, ErrEmptyOrder
}
total := money.Zero(prices[lines[0].SKU].Currency())
for _, l := range lines {
price, ok := prices[l.SKU]
if !ok {
return money.Money{}, fmt.Errorf("%w: %s", ErrUnknownSKU, l.SKU)
}
var err error
if total, err = total.Add(price.Times(l.Qty)); err != nil {
return money.Money{}, err
}
}
if coupon == nil {
return total, nil
}
return coupon.Apply(total)
}

func (c Coupon) Apply(subtotal money.Money) (money.Money, error) {
switch c.Kind {
case CouponPercent:
discount := subtotal.BasisPoints(c.PercentBps).RoundHalfEven() // rule agreed with finance
return subtotal.Sub(discount)
case CouponFixed:
return subtotal.SubFloorZero(c.Amount) // errors on currency mismatch
default:
return money.Money{}, fmt.Errorf("%w: %s", ErrUnknownCouponKind, c.Kind)
}
}

Now the interesting pricing cases — rounding at 10% of odd amounts, coupon larger than subtotal, mixed currencies — are fast table-driven tests with no database.

Step 6 — replace the provider switch with polymorphism​

Introduce payment.Provider (defined by the consumer), wrap the Stripe and PayPal clients in adapters that take money.Money and an idempotency key, and register them in main. Refund and webhook code migrate to the same interface in follow-up PRs, deleting their switches one by one. Adding MoMo is now a new adapter package plus one line of wiring.

Step 7 — extract the use case and fix the ordering​

The use case owns the business flow and fixes the ordering bugs: create the order as PENDING_PAYMENT first (idempotency key under a unique index), call the PSP outside any transaction with the same key, then record the outcome and an OrderPaid outbox event atomically. E-mail becomes a consumer of OrderPaid.

func (s *PlaceOrder) Handle(ctx context.Context, cmd PlaceOrderCmd) (Result, error) {
o, created, err := s.createPending(ctx, cmd) // tx1; returns the existing order on a retry
if err != nil {
return Result{}, err
}
if !created && o.Status != StatusPendingPayment {
return resultOf(o), nil // idempotent replay of a finished request
}

provider, err := s.providers.For(cmd.Method)
if err != nil {
return Result{}, err
}
charge, err := provider.Charge(ctx, payment.ChargeRequest{
Reference: string(o.ID),
Amount: o.Total,
Token: cmd.CardToken,
IdempotencyKey: cmd.IdempotencyKey,
})
var unknown *payment.UnknownOutcomeError
switch {
case errors.As(err, &unknown):
return resultOf(o), nil // stays PENDING_PAYMENT; reconciliation resolves it
case err != nil:
return Result{}, s.markFailed(ctx, o, err)
}
return s.markPaid(ctx, o, charge) // tx2: status + outbox OrderPaid
}

Step 8 — the final handler​

func (h *Handler) Checkout(w http.ResponseWriter, r *http.Request) {
var req checkoutRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "malformed JSON")
return
}
cmd, err := req.toCommand(r.Header.Get("Idempotency-Key"))
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
res, err := h.placeOrder.Handle(r.Context(), cmd)
if err != nil {
writeDomainError(w, err) // maps declines, unknown SKU, etc. to 4xx; logs 5xx once
return
}
status := http.StatusCreated
if res.Status == order.StatusPendingPayment {
status = http.StatusAccepted
}
writeJSON(w, status, checkoutResponse{OrderID: string(res.OrderID), Total: res.Total.String(), Status: string(res.Status)})
}

The characterization tests, now updated for the deliberate fixes, still pass; new unit tests cover pricing and the use case with fakes; one integration test covers the whole flow. Each step was a separate, reviewable PR — some pure refactors approved in minutes, the behavior changes reviewed carefully with finance in the loop.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Continuous refactoring (boy-scout rule, preparatory refactoring)Cheap, low risk, keeps design healthyNeeds discipline and tests; hard to show on a roadmapDefault for every team
Dedicated refactoring projectCan tackle deep structural problemsCompetes with features; risk of never finishingA hotspot blocks the roadmap and has a clear end state
Big-bang rewriteClean slateFeature freeze; rediscovers every hidden rule; very high risk in money systemsAlmost never; maybe for small, well-specified components
Strangler fig / branch by abstractionIncremental, reversible, delivers value earlyTwo systems coexist for a while; routing complexityReplacing large components or legacy systems
Shadow comparison in productionCatches real-world edge cases before switch-overExtra compute, mismatch triage effortPricing, fees, interest, ledger calculations

In practice​

  • Where to refactor first: hotspots — files with both high change frequency and high complexity. git log churn per file combined with a complexity metric (for example gocognit) finds them in minutes; Adam Tornhill's Your Code as a Crime Scene formalizes the approach.
  • When: right before a feature in that area (preparatory refactoring — "make the change easy, then make the easy change"), when you touch code anyway (leave it a bit better), and when a defect reveals a structural cause.
  • How big: a reviewer should be able to verify a pure refactoring PR in roughly 15–30 minutes. Mechanical renames across many files are fine if they are only renames.
  • Tooling: gopls rename and extract actions, gofmt -r rewrites, go vet, and linters (dupl, gocognit, errcheck) to track progress. For untested legacy code, introduce seams (interfaces at I/O boundaries, injectable clocks) using the safest possible edits before writing tests.
  • System scale: the same moves apply to architecture. Parallel change for API fields and columns; branch by abstraction to swap a PSP SDK or ORM in place; strangler fig to peel endpoints off a monolith (see Legacy Modernization & Migration).

Common pitfalls​

  • Refactoring without tests. Symptom: a "pure refactor" PR followed by a rise in payment failures or reconciliation mismatches.
  • Mixing behavior changes into refactors. Symptom: a rounding change hidden in a 600-line diff, found by finance at month-end close.
  • Silent rounding changes when introducing Money. Symptom: totals differ by one minor unit from invoices, receipts or the PSP's settlement report.
  • Renaming exported APIs, JSON fields or columns in place. Symptom: consumers break on deploy; mobile apps on older versions fail.
  • Abstracting during the refactor. Symptom: you introduce strategy, factory and plugin registry for two cases; the code is now harder to read than before.
  • Endless refactor branches. Symptom: a long-lived branch with 80 commits that can no longer be merged; work is abandoned. Merge small steps to main continuously.
  • Rewriting instead of refactoring. Symptom: the new system ships a year late and misses rules the old code encoded in obscure branches.

Interview angle​

  • Prompts: "You inherit an untested legacy payment module — what do you do?", "Tell me about a significant refactoring you led", "How do you justify refactoring time to the business?"
  • A strong answer: find hotspots, add characterization tests and seams, fix dangerous bugs as explicit changes, refactor in small mergeable steps, use parallel change and feature flags at boundaries, shadow-compare money calculations, and measure outcomes (lead time, incident rate, change failure rate). Business justification: cost and risk of the next features in that area, plus defects removed.
  • Expected follow-ups: "How do you refactor without tests?" (seams, characterization), "How do you avoid breaking consumers?" (parallel change, contract tests), "Rewrite or refactor?" (strangler fig unless the component is small and well specified).
  • Red flags: "we'll rewrite it", refactoring as a separate multi-month phase with no deliverables, no mention of tests, or treating float64 money as acceptable.

Self-check​

1. What distinguishes a refactoring from a behavior change, and why keep them in separate commits or PRs?

A refactoring preserves observable behavior — same outputs, side effects and errors for every input; only structure changes. Keeping it separate lets reviewers verify it quickly (tests unchanged and green) and lets behavior changes get focused scrutiny and their own rollback. Mixed PRs hide risky changes inside large diffs.

2. Why is int64(price*100) dangerous with float64 prices, and what do you replace it with?

Most decimal amounts are not exactly representable in binary floating point; 19.99*100 is 1998.9999999999998 and the cast truncates it to 1998. Errors accumulate in sums and comparisons fail. Replace with a Money value type holding integer minor units plus currency (or a decimal type for higher precision), with explicit rounding and allocation rules and currency-mismatch checks.

3. How do you split 100.00 between three sellers without losing or creating a cent?

Compute each share in minor units with integer division (3,333 each, 9,999 total), then distribute the remainder (1) one unit at a time to the parts in a defined order, giving 33.34, 33.33, 33.33. The invariant — parts sum to the original — should be enforced by tests, ideally property-based.

4. What are characterization tests and why do they deliberately assert buggy behavior?

Tests that capture what legacy code currently does, used as a safety net before refactoring. They assert current behavior, bugs included, because the goal is to detect any change. Bugs are marked (for example with a BUG: comment) and fixed later as explicit behavior changes, with the test expectation flipped in the same PR.

5. You find the same switch over payment providers in four packages. What is the smell and the refactoring?

Repeated switch on type, which causes shotgun surgery whenever a provider is added — and the copy without a default case becomes a silent bug. Replace conditional with polymorphism: a Provider interface implemented by an adapter per PSP, a registry built in main, and migration of each switch one PR at a time.

6. Scenario: introducing Money changes some order totals by one cent compared to production. Is your refactor wrong?

Not necessarily — the old float code was probably wrong (truncation or accumulated error). But it is a behavior change, so it must be treated as one: confirm the correct rounding rule with finance, update the characterization tests explicitly, communicate the change, consider shadow comparison and a feature flag, and check downstream consumers (invoices, settlement files, reconciliation) that may compare against the old values.

7. What is wrong with charging the card before inserting the order, and what ordering fixes it?

If the insert fails after a successful charge, the customer has paid and no order exists; a retry may charge again. Create the order first as PENDING_PAYMENT with an idempotency key, charge outside the transaction reusing that key, then record the outcome and an outbox event atomically. An unknown PSP outcome leaves the order pending for reconciliation.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Reproduce the worked example yourself.

  1. Copy the Step 0 handler into a small repository with a products and coupons table (Postgres via testcontainers) and fake Stripe/PayPal clients that record calls.
  2. Write characterization tests for at least six cases, including the truncation bug and the unknown-provider bug.
  3. Perform Steps 2–8 as separate commits. After each commit, run go test -race ./...; every commit must be green.
  4. Add table-driven tests for Quote (rounding at percent discounts, coupon bigger than subtotal, currency mismatch) and for the use case with an UnknownOutcomeError from the PSP fake.

Done when: the final handler is roughly 25 lines or fewer, no float64 touches money, there is no SQL in the handler, the provider switch is gone, a duplicate request with the same Idempotency-Key charges once, and git log --oneline reads as a clear story where refactoring and behavior-change commits are distinguishable.

Further reading​

  • Martin Fowler, Refactoring: Improving the Design of Existing Code, 2nd ed. (2018) — the smells and moves catalog; also the online catalog at refactoring.com.
  • Michael Feathers, Working Effectively with Legacy Code (2004) — seams and characterization tests.
  • Kent Beck, Tidy First? (2023) — small structural changes and when to make them.
  • Joshua Kerievsky, Refactoring to Patterns (2004) — refactoring toward (and away from) design patterns.
  • Adam Tornhill, Your Code as a Crime Scene, 2nd ed. (2024) — finding hotspots from version-control history.
  • Martin Fowler's bliki: "StranglerFigApplication", "BranchByAbstraction", and Danilo Sato's "ParallelChange".
Finished this page?

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