Shelves / Software Architecture
SA·135
Clean Code
Writing code that is cheap to read and change: why maintainability is economics, naming as design, cohesion and coupling (with the types of each), small focused functions and command-query separation, modules and information hiding, boundaries and anti-corruption at the edges, error handling across paradigms (exceptions, error values, Result types, panics), immutability and value semantics, dependency management at code and package level, comments and documentation, refactoring safely, code review, and where "clean code" dogma goes too far, illustrated in Java, Kotlin, Go, Rust, Python, TypeScript, C, C++, Zig and Haskell.
Start here: code is read far more than it is written
Clean code is code a colleague (or you, in six months) can understand and change quickly and safely. It isn't about style preferences; it's about the cost of the next change. The habits are simple to state: good names, small functions that do one thing, few branches per function, related things kept together, dependencies passed in, and no surprises.
Where complexity actually hurts: hotspots
Complexity only costs money where code changes. The requests library (245 functions) measured two ways:
most complex functions (cyclomatic complexity, lines):
21 51 models.py _encode_files
19 81 adapters.py send
19 48 models.py prepare_body
functions with complexity > 10: 13 of 245 (5.3%)
hotspots = commits since 2016 × total complexity of the file:
utils.py 110 commits × 201 = 22,110
models.py 100 commits × 196 = 19,600
sessions.py 82 commits × 113 = 9,266
cookies.py 20 commits × 119 = 2,380 ← complex, but rarely changed
cookies.py is fairly complex but rarely touched; cleaning it would cost effort and save little. utils.py and models.py are both complex and changed constantly, so every improvement there pays back on every future change. This hotspot view (from Adam Tornhill's Your Code as a Crime Scene) tells you where clean-code effort is worth spending.
Refactoring safely: prove the behaviour didn't change
Refactoring means changing structure without changing behaviour. The Start Here checkout's pricing was pulled out of the big function into three small ones (complexity 13 → 3, 3 and 2). To prove nothing changed, a property test compared old and new on 2,000 generated orders:
new order_total == old checkout total, 2,000 random orders: 1 passed in 3.22s
Then a one-character bug was slipped into the refactoring: the member discount threshold became >= instead of >:
2,000 random orders, bug present: 1 passed ← missed it
plus one explicit example with a total of exactly ₹500: AssertionError: assert 450.0 == 475.0
Random orders almost never total exactly ₹500, so random testing alone missed the off-by-one. One hand-picked boundary example caught it immediately. Characterization tests (recording what the old code does) plus boundary cases are how you refactor code that has no tests.
How deep to go in clean code
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Recognise unclear names, long functions, deep nesting and hidden side effects |
| L2 | Write small, well-named functions and refactor in small steps with tests green |
| L3 | Explain cohesion and coupling types, CQS, information hiding and why each reduces change cost |
| L4 | Find hotspots from metrics and history, and refactor legacy code safely with characterization tests |
| L5 | Set code-structure conventions and quality gates for a codebase |
| L6 | Run code-health programmes across an organisation with measurable outcomes |
Why clean code matters
Code is read far more often than it's written: by teammates in review, by you in six months, by the on-call engineer at 3 am, by the person adding the next feature. The cost of a codebase over its lifetime is dominated by change, and the cost of change is dominated by understanding: finding where to change, predicting consequences, and verifying the result.
"Clean code" is shorthand for code whose intent is obvious, whose parts are independent enough to change one without breaking others, and whose failures are visible and handled. It's not about aesthetics, line counts or following a book literally; it's economics:
- Low cognitive load: a reader can hold the relevant context in their head (Vol. 1 cognition limits: roughly a handful of things at once).
- Locality: to understand or change a behaviour, you look in one place.
- Safety: types, tests and structure catch mistakes before production.
John Ousterhout (A Philosophy of Software Design) frames complexity as anything that makes a system hard to understand and modify, showing up as change amplification (one change requires edits in many places), cognitive load (how much you must know to make a change) and unknown unknowns (it's not obvious what must change). Most clean-code practices attack one of these three.
Naming
Names are the primary documentation of code. A good name tells the reader what something is or does and why it exists, at the right level of abstraction, using the domain's language (chapter 138).
Guidelines
| Guideline | Poor | Better |
|---|---|---|
| Reveal intent | d, data, tmp, list2 |
elapsedDays, pendingInvoices |
| Use domain words | processRecords() |
settleMerchantPayouts() |
| Name by role, not type | stringList, userMap |
blockedEmails, usersById |
| Booleans as predicates | flag, status |
isExpired, hasPaymentMethod, canRetry |
| Functions as verbs, values as nouns | invoice() (does it create? fetch?) |
createInvoice(), invoiceFor(order) |
| Consistent vocabulary | fetchUser, getOrder, retrieveCart |
One verb per concept: findX for queries that may return nothing, getX when it must exist |
| Units in names when types don't carry them | timeout = 30 |
timeoutSeconds = 30, or better a Duration type |
| Avoid noise words | UserData, OrderInfo, ManagerHelperUtil |
User, Order, a name saying what it does |
| Scope-proportional length | Long names for loop indices; one-letter globals | i in a 3-line loop is fine; package-level names deserve precision |
Language conventions matter: Go prefers short names in small scopes (r for a reader, ctx) and package-qualified naming (http.Client, not http.HTTPClient: avoid stutter); Java and C# favour descriptive camel/Pascal case; Rust uses snake_case functions and UpperCamelCase types with conversion conventions (as_, to_, into_); Python follows PEP 8; C relies on prefixes for namespacing (sqlite3_open); Haskell embraces short names for highly generic code (f, xs) because the types carry the meaning.
Names reveal design problems
If you can't name something well, the abstraction is probably wrong: OrderManager, DataProcessor, Utils and Helper usually mean "a grab bag of unrelated responsibilities". A function named validateAndSaveAndNotify is three functions. Struggling for a name is a design signal worth listening to.
Cohesion and coupling
The two most important structural properties of code (Larry Constantine, 1970s), still the best predictors of maintainability:
- Cohesion: how strongly the elements inside a module belong together. High cohesion: everything in the module serves one purpose and changes for the same reasons.
- Coupling: how strongly different modules depend on each other. Low coupling: you can change one module without changing (or even understanding) others.
Goal: high cohesion, low coupling. Things that change together live together; things that change independently are separated by narrow, stable interfaces.
Kinds of cohesion (weakest to strongest)
| Kind | Elements grouped because… | Example |
|---|---|---|
| Coincidental | No reason | Utils with string padding, date parsing and HTTP retries |
| Logical | Same category of thing | Validators class validating unrelated entities |
| Temporal | Run at the same time | startup() initialising logging, cache and payments |
| Procedural | Steps in a sequence | A function doing parse → validate → save → email |
| Communicational | Operate on the same data | Functions all working on an Order record |
| Sequential | Output of one is input of the next | A pipeline stage chain |
| Functional | Together achieve one well-defined purpose | PriceCalculator |
Kinds of coupling (worst to best)
| Kind | Dependency | Example |
|---|---|---|
| Content | One module reaches into another's internals | Modifying another class's private fields via reflection; sharing database tables between services |
| Common/global | Shared global mutable state | Global singletons, static mutable config |
| Control | Passing flags that steer the other's logic | render(user, isAdmin, isPreview, skipCache) |
| Stamp | Passing whole structures when only parts are used | Passing the entire Order to compute a shipping zone from its postcode |
| Data | Passing only the needed primitive/value data | shippingZone(postcode) |
| Message | Communicating via messages/events with no shared state | Events on a bus (chapter 139) |
Modern additions: temporal coupling (must call init() before use()), deployment coupling (must release together), semantic coupling (both sides must agree on meaning not captured in types), and connascence (Meilir Page-Jones), a vocabulary for degrees of coupling: connascence of name (rename both), of type, of meaning (magic values), of position (argument order), of algorithm (both must use the same hashing), of timing, of identity. Prefer weaker forms and keep stronger forms local (within a function or class, not across modules).
Practical heuristics
- Change together, live together: if a feature change always touches files in five packages, reorganise by feature/domain rather than by technical layer.
- Depend on the minimum: accept the narrowest type that works (an interface with one method, a value instead of an entity).
- Avoid boolean/flag parameters that select behaviour; split into separate functions or use an enum/strategy.
- Law of Demeter ("talk to friends, not strangers"):
order.getCustomer().getAddress().getCity()couples you to three structures' shapes; askorder.shippingCity()or pass what's needed. (Fluent builders and data pipelines are fine; the concern is navigating object graphs you don't own.)
Functions
Small and focused
A function should do one thing at one level of abstraction. That doesn't mean "as few lines as possible" (tiny functions scattered everywhere increase cognitive load too); it means a reader can understand what the function does from its name and see how from a body that reads like a summary.
// Before: one method mixing levels of abstraction (HTTP parsing, validation, pricing, persistence, email)
public Response checkout(HttpRequest req) {
var json = new JSONObject(req.body());
if (!json.has("items") || json.getJSONArray("items").isEmpty()) return Response.badRequest("no items");
BigDecimal total = BigDecimal.ZERO;
for (int i = 0; i < json.getJSONArray("items").length(); i++) { /* ... 30 lines of pricing ... */ }
// ... SQL insert ..., SMTP send ...
return Response.ok();
}
// After: the top level reads like the business process; details live in focused collaborators
public OrderConfirmation checkout(CheckoutRequest request) {
Cart cart = carts.load(request.cartId());
Quote quote = pricing.quote(cart, request.customer());
Order order = orders.place(cart, quote);
notifications.orderPlaced(order);
return OrderConfirmation.of(order);
}
// Go: same idea; error handling stays visible at each step
func (s *CheckoutService) Checkout(ctx context.Context, req CheckoutRequest) (Confirmation, error) {
cart, err := s.carts.Load(ctx, req.CartID)
if err != nil {
return Confirmation{}, fmt.Errorf("load cart %s: %w", req.CartID, err)
}
quote, err := s.pricing.Quote(ctx, cart, req.Customer)
if err != nil {
return Confirmation{}, fmt.Errorf("quote: %w", err)
}
order, err := s.orders.Place(ctx, cart, quote)
if err != nil {
return Confirmation{}, fmt.Errorf("place order: %w", err)
}
s.notifications.OrderPlaced(ctx, order) // fire-and-forget via outbox/queue
return ConfirmationFor(order), nil
}
# Python
def checkout(request: CheckoutRequest) -> OrderConfirmation:
cart = carts.load(request.cart_id)
quote = pricing.quote(cart, request.customer)
order = orders.place(cart, quote)
notifications.order_placed(order)
return OrderConfirmation.of(order)
-- Haskell: the pipeline is explicit in the types; effects are visible in the signature
checkout :: CheckoutRequest -> App OrderConfirmation
checkout req = do
cart <- loadCart (cartId req)
quote <- priceQuote cart (customer req)
order <- placeOrder cart quote
notifyOrderPlaced order
pure (confirmationFor order)
Parameters and return values
- Few parameters (0–3 typically). Many parameters suggest a missing concept: group them into a value object (
DateRangeinstead offrom, to;Moneyinstead ofamount, currency). - Prefer explicit inputs and outputs to hidden state. A function that reads globals or mutates its arguments is harder to reason about and test.
- Avoid output parameters (mutating an argument to return a result) except in performance-critical C/C++/Zig code where it's idiomatic (and documented).
- Return rich types instead of sentinel values:
Optional<T>/Option<T>,Result<T, E>, discriminated unions, rather thannull,-1or empty strings meaning "not found".
Command-query separation
Bertrand Meyer's command-query separation (CQS): a function should either change state (command, returns nothing or an acknowledgement) or answer a question (query, no side effects), not both. Queries become safe to call anywhere (tests, logging, debugging) and reasoning becomes easier. Pragmatic exceptions exist (stack.pop(), map.computeIfAbsent, atomic operations like incrementAndGet where splitting would introduce races).
Pure functions and side effects
A pure function returns the same output for the same input and has no observable side effects. Pure functions are trivial to test, cache, parallelise and reason about. A useful structure in any paradigm is functional core, imperative shell (Gary Bernhardt): put decisions and calculations in pure functions; keep I/O (database, network, clock, randomness) in a thin outer layer that calls them.
// Rust: pure pricing core; the shell gathers inputs (prices, time) and persists results
pub fn quote(items: &[LineItem], rules: &DiscountRules, today: NaiveDate) -> Quote {
let subtotal: Money = items.iter().map(|i| i.unit_price * i.qty).sum();
let discount = rules.applicable(today).map(|r| r.apply(subtotal)).unwrap_or(Money::ZERO);
Quote { subtotal, discount, total: subtotal - discount }
}
// Tests call quote(...) with literal data: no mocks, no clock, no database.
Modules
Information hiding
David Parnas (1972, "On the Criteria To Be Used in Decomposing Systems into Modules") argued that modules should be organised around design decisions likely to change, each module hiding one such decision behind an interface. Not around steps in a flowchart. This is the foundation of encapsulation and of good module boundaries at every scale (classes, packages, services).
Ousterhout's corollary: prefer deep modules: a simple interface hiding substantial functionality (Unix file I/O: open/read/write/close hiding file systems, caching, devices). Shallow modules (complex interface, little functionality behind it) add cognitive cost without hiding much: many tiny pass-through classes are a smell, not a virtue.
Module mechanisms across languages
| Language | Module unit | Visibility control |
|---|---|---|
| Java | Packages; JPMS modules (module-info.java with exports/requires) |
public/protected/package-private/private; non-exported packages invisible outside a module; sealed hierarchies |
| Kotlin | Packages, Gradle modules | internal = visible within a compilation module |
| Go | Packages (directory); modules (go.mod) for versioning |
Capitalised = exported; internal/ directories importable only by the parent tree |
| Rust | Crates and mod hierarchy |
pub, pub(crate), pub(super); private by default |
| Python | Modules/packages | Convention (_private), __all__; enforce boundaries with tools (import-linter, Tach) |
| TypeScript | ES modules, packages in monorepos | export; package exports maps; lint rules (eslint-plugin-boundaries, dependency-cruiser) |
| C | Translation units + headers | static for file-private; opaque pointers (typedef struct parser parser;) hide struct layout |
| C++ | Headers or C++20 modules (export module) |
private/public; modules stop macro and implementation leakage; pImpl idiom |
| Zig | Files are structs; packages via build system | pub declarations; everything else file-private |
| Haskell | Modules with explicit export lists | Export only smart constructors to protect invariants |
/* C: an opaque type hides representation; callers can't depend on struct fields */
/* ring_buffer.h */
typedef struct ring_buffer ring_buffer; /* incomplete type */
ring_buffer *rb_create(size_t capacity);
int rb_push(ring_buffer *rb, int value); /* 0 ok, -1 full */
int rb_pop(ring_buffer *rb, int *out); /* 0 ok, -1 empty */
void rb_destroy(ring_buffer *rb);
/* ring_buffer.c */
struct ring_buffer { int *data; size_t head, tail, len, cap; }; /* free to change */
-- Haskell: export the type but not its constructor; the smart constructor enforces the invariant
module Email (Email, mkEmail, emailText) where
import qualified Data.Text as T
newtype Email = Email T.Text
mkEmail :: T.Text -> Either String Email
mkEmail t | "@" `T.isInfixOf` t && T.length t <= 254 = Right (Email (T.toLower t))
| otherwise = Left "invalid email"
emailText :: Email -> T.Text
emailText (Email t) = t
Boundaries
A boundary is where your code meets something you don't control or that changes for different reasons: third-party libraries, frameworks, databases, external APIs, the UI, other teams' services. Clean boundaries:
- Wrap third-party APIs behind your own interfaces expressed in your domain's terms (an
ExchangeRatesport instead of calling a vendor SDK from business logic). You limit the blast radius of upgrades and vendor changes, and you can test with fakes (Vol. 11 ch. 115). - Translate at the edge: convert external representations (JSON DTOs, ORM entities, vendor models) into internal domain types at the boundary, validate there ("parse, don't validate": once data is inside, its types guarantee it's valid), and convert back on the way out.
- Keep frameworks at the edges: business rules shouldn't import web-framework or ORM types. This is the essence of hexagonal/clean architecture (chapter 139).
- Learning tests: when adopting a library, write small tests capturing how you use it; they document assumptions and catch behaviour changes on upgrade.
// "Parse, don't validate": turn untrusted input into a type that guarantees validity
import { z } from "zod";
const PlaceOrderInput = z.object({
customerId: z.string().uuid(),
items: z.array(z.object({ sku: z.string().min(1), qty: z.number().int().positive() })).nonempty(),
});
type PlaceOrder = z.infer<typeof PlaceOrderInput>; // inside the boundary, items is non-empty, qty > 0
export function handle(body: unknown): PlaceOrder {
return PlaceOrderInput.parse(body); // throws at the edge; core code never re-checks
}
Error handling
Make failure explicit
Errors are part of a function's contract. Clean error handling makes failures visible, specific and handled at the right level:
- Fail fast on programmer errors (violated preconditions, impossible states): assertions, panics,
IllegalStateException. - Handle expected failures (not found, validation errors, timeouts, conflicts) as part of normal control flow with precise types.
- Don't swallow errors (
catch (Exception e) {},_ = err), and don't log-and-rethrow at every layer (duplicate noise). Handle or propagate with context, and log once at the boundary. - Add context when propagating ("load cart 42: connection refused"), preserving the cause.
- Clean up resources reliably: try-with-resources,
defer, RAII/Drop, context managers,errdefer. - Fail closed for security decisions (Vol. 10 ch. 108).
Error models across languages
| Language | Primary mechanism | Notes |
|---|---|---|
| Java/Kotlin/C# | Exceptions (Java: checked and unchecked) | Checked exceptions document failures but compose poorly with lambdas; many teams use unchecked domain exceptions or Result-like sealed types; Kotlin has no checked exceptions and offers Result/runCatching and sealed hierarchies |
| Go | Error values returned explicitly ((T, error)) |
errors.Is/As, wrapping with %w, errors.Join; panic only for truly unrecoverable bugs |
| Rust | Result<T, E> and Option<T>; ? operator propagates |
panic! for bugs; thiserror for library error enums, anyhow for application context |
| Zig | Error unions (!T), try, catch, errdefer |
Error sets are inferred and checked at compile time; no hidden control flow |
| C | Return codes + errno/out-parameters |
Discipline required: check every return; goto cleanup pattern |
| C++ | Exceptions; std::expected<T,E> (C++23); error codes |
Many codebases (games, embedded, Google's style historically) disable exceptions; RAII ensures cleanup |
| Python | Exceptions | Specific exception classes, raise ... from err for chaining, context managers |
| TypeScript | Exceptions (untyped); Result-style unions in modern code |
unknown in catch; libraries like neverthrow/Effect for typed errors |
| Haskell | Maybe, Either, ExceptT; exceptions in IO |
Errors in types; effect systems |
// Rust: typed domain errors with thiserror; ? propagates with conversion
use thiserror::Error;
#[derive(Debug, Error)]
pub enum CheckoutError {
#[error("cart {0} not found")]
CartNotFound(CartId),
#[error("item {sku} out of stock")]
OutOfStock { sku: String },
#[error("payment declined: {0}")]
PaymentDeclined(String),
#[error(transparent)]
Storage(#[from] sqlx::Error), // infrastructure errors wrapped, not leaked as strings
}
pub async fn checkout(&self, cart_id: CartId) -> Result<OrderId, CheckoutError> {
let cart = self.carts.find(cart_id).await?.ok_or(CheckoutError::CartNotFound(cart_id))?;
self.inventory.reserve(&cart).await?;
let order_id = self.orders.place(&cart).await?;
Ok(order_id)
}
// Go: sentinel and typed errors, wrapped with context, inspected with errors.Is/As
var ErrCartNotFound = errors.New("cart not found")
type OutOfStockError struct{ SKU string }
func (e *OutOfStockError) Error() string { return "out of stock: " + e.SKU }
func (s *Service) Checkout(ctx context.Context, id CartID) (OrderID, error) {
cart, err := s.carts.Find(ctx, id)
if errors.Is(err, sql.ErrNoRows) {
return "", fmt.Errorf("checkout %s: %w", id, ErrCartNotFound)
}
if err != nil {
return "", fmt.Errorf("checkout %s: load cart: %w", id, err)
}
if err := s.inventory.Reserve(ctx, cart); err != nil {
return "", fmt.Errorf("checkout %s: %w", id, err)
}
return s.orders.Place(ctx, cart)
}
// at the HTTP boundary:
// var oos *OutOfStockError
// switch { case errors.Is(err, ErrCartNotFound): 404; case errors.As(err, &oos): 409; default: 500 }
// Java 25: sealed result types + pattern matching for expected outcomes; exceptions for the unexpected
public sealed interface CheckoutResult {
record Placed(OrderId id) implements CheckoutResult {}
record OutOfStock(String sku) implements CheckoutResult {}
record PaymentDeclined(String reason) implements CheckoutResult {}
}
CheckoutResult result = checkout.run(cartId);
return switch (result) { // exhaustive: compiler checks all cases
case CheckoutResult.Placed p -> ResponseEntity.status(201).body(p.id());
case CheckoutResult.OutOfStock o -> ResponseEntity.status(409).body(problem("out of stock", o.sku()));
case CheckoutResult.PaymentDeclined d -> ResponseEntity.status(402).body(problem("declined", d.reason()));
};
// Zig: error unions, try, and errdefer for cleanup on the error path only
const CheckoutError = error{ CartNotFound, OutOfStock, OutOfMemory };
fn checkout(allocator: std.mem.Allocator, store: *Store, id: CartId) CheckoutError!OrderId {
const cart = store.findCart(id) orelse return error.CartNotFound;
const reservation = try store.reserve(allocator, cart); // propagates OutOfStock / OutOfMemory
errdefer store.release(reservation); // runs only if a later step fails
return try store.placeOrder(allocator, cart, reservation);
}
/* C: single exit with goto-based cleanup; every call checked */
int export_report(const char *path, const report *r) {
int rc = -1;
FILE *f = fopen(path, "w");
if (!f) return -1;
char *buf = malloc(4096);
if (!buf) goto close_file;
if (render_report(r, buf, 4096) != 0) goto free_buf;
if (fputs(buf, f) == EOF) goto free_buf;
rc = 0;
free_buf:
free(buf);
close_file:
if (fclose(f) != 0) rc = -1;
return rc;
}
Where to handle errors
- Lowest level that can do something useful (retry a transient error, fall back to a default, translate to a domain error).
- Boundaries translate errors into the outside world's language: HTTP status codes and problem details, exit codes, user-facing messages, without leaking internals.
- Top level logs unexpected errors with context and correlation IDs, and returns a generic failure.
Immutability
Why immutability helps
An immutable value can't change after creation. Benefits:
- Reasoning: a value you're holding won't change under you; no "who modified this?" debugging.
- Thread safety: immutable data can be shared across threads without locks (Vol. 2 concurrency).
- Safe sharing and caching: hash keys stay valid; defensive copies become unnecessary.
- Equality by value: two
Money(100, INR)are interchangeable (value objects, chapter 138). - Undo, history, time travel: keep old versions cheaply (persistent data structures, Redux-style state).
Costs: allocation and copying (mitigated by persistent/structural-sharing data structures and modern GCs), and some algorithms are naturally in-place (performance-critical code in C/C++/Rust/Zig uses controlled mutation).
Immutability across languages
| Language | Tools |
|---|---|
| Java | record, final fields, List.of/Map.of (unmodifiable), avoid setters; "withers" returning modified copies |
| Kotlin | val, data class with copy(), read-only collection interfaces (List vs MutableList), kotlinx.collections.immutable |
| C# | record, init setters, readonly struct, ImmutableArray |
| Go | No language-level immutability: unexported fields + no setters, return copies, value receivers; be careful with slices and maps (aliasing) |
| Rust | Immutable by default (let vs let mut); the borrow checker enforces aliasing XOR mutability at compile time |
| Python | @dataclass(frozen=True), NamedTuple, tuples, frozenset, MappingProxyType |
| TypeScript | readonly properties, ReadonlyArray, as const, Object.freeze (shallow, runtime) |
| C | const (shallow; pointers to const) |
| C++ | const, constexpr, const member functions, value semantics |
| Zig | const by default for declarations; var for mutation; pointer constness |
| Haskell | Everything immutable; mutation only via explicit effect types (IORef, ST) |
// Kotlin: immutable value with copy-based updates
data class Address(val line1: String, val city: String, val postcode: String)
data class Customer(val id: CustomerId, val name: String, val address: Address)
val moved = customer.copy(address = customer.address.copy(city = "Hyderabad", postcode = "500039"))
// customer is unchanged; moved is a new value
// Go: protect invariants by keeping fields unexported and returning copies of slices
type Order struct {
id OrderID
items []LineItem
}
func (o Order) Items() []LineItem {
return slices.Clone(o.items) // callers can't mutate the order's internal slice
}
Value semantics vs reference semantics: in C++, Rust, Go structs, C# structs and Swift structs, assignment copies values; in Java/Python/JS, variables hold references to shared objects, so mutation through one reference is visible through all. Many bugs come from unintended aliasing of mutable objects.
Dependency management
Code-level dependencies
- Depend on abstractions at volatile boundaries: business logic depends on interfaces it defines (ports), implementations plug in (Dependency Inversion, chapter 136).
- Make dependencies explicit: constructor/function parameters rather than hidden
newcalls, service locators or globals. Explicit dependencies are visible, testable and replaceable (dependency injection, chapter 137). - Avoid cyclic dependencies between modules/packages: cycles mean modules can't be understood, tested or released independently. Go forbids import cycles; tools detect them elsewhere (ArchUnit, JDepend, Madge, cargo's crate graph is acyclic by construction).
- Stable dependencies principle (Robert Martin): depend in the direction of stability: volatile modules (UI, adapters) depend on stable ones (domain), not vice versa.
Package-level dependencies
- Add third-party packages deliberately: each brings code, transitive dependencies, security exposure (Vol. 10 ch. 112) and upgrade work. Prefer the standard library and well-maintained, widely used packages.
- Pin and lock versions (lockfiles), automate updates (Renovate/Dependabot), and keep dependencies current in small steps rather than painful big-bang upgrades.
- Isolate heavy frameworks behind boundaries so they can be upgraded or replaced.
- Monitor licences and vulnerabilities.
Comments and documentation
- Code says what and how; comments say why: the reason for a non-obvious choice, the business rule's origin, a workaround for a known bug (with a link), performance or security considerations.
- Interface comments (Javadoc, Go doc comments, Rust doc comments with runnable examples, Python docstrings) document contracts: what it does, parameters, return values, errors, invariants, thread safety. Ousterhout recommends writing these first, as a design tool.
- Delete commented-out code (version control remembers), stale comments (worse than none) and comments restating the code (
i++ // increment i). - Architecture docs: README per module, ADRs for decisions (chapter 142), diagrams-as-code (C4, Mermaid) kept close to code.
/// Splits `total` into `parts` amounts that differ by at most one minor unit
/// and sum exactly to `total` (largest remainder method).
///
/// # Panics
/// Panics if `parts` is zero.
///
/// # Examples
/// ```
/// use money::split;
/// assert_eq!(split(100, 3), vec![34, 33, 33]);
/// ```
pub fn split(total: i64, parts: usize) -> Vec<i64> { /* ... */ }
// `cargo test` runs the example in the doc comment, so documentation can't silently rot.
Refactoring
Refactoring (Martin Fowler) is changing code's structure without changing its behaviour, in small, safe steps, each verified by tests. It's how code stays clean over time: the "boy scout rule" (leave the code a bit better than you found it) and "make the change easy, then make the easy change" (Kent Beck).
Common refactorings (most automated in IDEs: IntelliJ, Rider, VS Code with language servers, rust-analyzer, gopls):
| Smell | Refactoring |
|---|---|
| Long function | Extract function; replace temp with query; decompose conditional |
| Large class / god object | Extract class; move function; split by responsibility |
| Long parameter list | Introduce parameter object / value object |
Primitive obsession (String email, long cents) |
Replace primitive with value object (Email, Money) |
| Feature envy (method mostly uses another class's data) | Move function to that class |
| Switch/if chains on type codes | Replace conditional with polymorphism, strategy or exhaustive pattern matching over sealed types |
| Duplicated code | Extract function/module, but beware premature abstraction |
| Shotgun surgery (one change, many files) | Move related code together |
| Divergent change (one module changes for many reasons) | Split module |
| Data clumps (same fields always together) | Extract value object |
| Temporary field, null checks everywhere | Introduce special case / Option types |
Safety net: characterisation tests for legacy code (capture current behaviour before changing, Michael Feathers' Working Effectively with Legacy Code), small commits, and continuous integration.
Code review and consistency
- Automate the trivial: formatters (gofmt, rustfmt, Black/Ruff, Prettier, google-java-format/Spotless, clang-format, zig fmt) and linters (Ruff, ESLint, Clippy, golangci-lint, Error Prone, SpotBugs, clang-tidy) end style debates and catch common bugs.
- Review for design and intent: naming, boundaries, error handling, tests, security, operability; small pull requests reviewed quickly.
- Shared conventions documented in the repository (contributing guide, architecture overview, ADRs).
- Architecture tests enforce boundaries automatically (chapter 140).
When clean-code advice goes too far
Rules of thumb become harmful when applied without judgement:
- Over-abstraction: interfaces with one implementation "just in case", factories for objects that never vary, layers that only forward calls (shallow modules). Abstraction should be earned by real variation or a real boundary (YAGNI: "you aren't gonna need it").
- Tiny-function fragmentation: splitting a clear 30-line function into ten 3-line functions scattered across a file can make it harder to follow.
- DRY taken literally: merging code that looks similar but represents different concepts creates coupling between things that change for different reasons. Prefer duplication over the wrong abstraction (Sandi Metz); apply the "rule of three" before extracting.
- Ignoring performance and context: data-oriented design in games and systems code (arrays of structs vs structs of arrays, avoiding virtual dispatch in hot loops) legitimately trades some "cleanliness" for cache efficiency; Casey Muratori's critique of "clean code" performance costs is worth knowing. Measure, then decide.
- Dogma over team conventions: consistency within a codebase usually matters more than any individual rule.
The test is always: does this make the code easier to understand and change for the people who work on it?
Lab: measuring code health and refactoring safely
lizard 1.24.3 and radon 6.0.1 on the lab machine, the psf/requests repository cloned from GitHub (6,496 commits, last commit 2026-10-26), and Hypothesis with pytest for the refactoring check.
Experiment 1: complexity in a real library
lizard src/requests -l python --csv > liz.csv # per function: NLOC, CCN, tokens, params, length
| Function | File | CCN | NLOC |
|---|---|---|---|
_encode_files |
models.py | 21 | 51 |
send |
adapters.py | 19 | 81 |
build_digest_header |
auth.py | 19 | 68 |
prepare_body |
models.py | 19 | 48 |
should_bypass_proxies |
utils.py | 19 | 37 |
prepare_url |
models.py | 18 | 52 |
13 of 245 functions (5.3%) exceed CCN 10, a common review threshold. Read those functions: most are complex because the problem is (multipart encoding, digest auth, proxy rules), which is the usual finding. The goal isn't zero complex functions; it's that complexity lives where it must and is well tested.
Experiment 2: hotspots
git log --since=2016-01-01 --name-only --format= -- src/requests requests | grep '\.py$' | sort | uniq -c | sort -rn
| File | Commits since 2016 | Total CCN | Max CCN | Hotspot score |
|---|---|---|---|---|
| utils.py | 110 | 201 | 19 | 22,110 |
| models.py | 100 | 196 | 21 | 19,600 |
| sessions.py | 82 | 113 | 15 | 9,266 |
| adapters.py | 54 | 74 | 19 | 3,996 |
| cookies.py | 20 | 119 | 9 | 2,380 |
| auth.py | 28 | 57 | 19 | 1,596 |
(The package moved from requests/ to src/requests/ during that period; the paths were merged.) Two more history signals worth computing on your own code: change coupling (files that change in the same commits, which reveals hidden dependencies) and author count per file (many authors on one complex file predicts defects). Tools such as CodeScene, code-maat or a 20-line script over git log produce them.
Experiment 3: a differential test for a refactoring
@settings(max_examples=2000)
@given(items, st.booleans())
@example([{"type": "thali", "price": 250, "qty": 2}], True) # total exactly ₹500
def test_new_pricing_matches_old(its, member):
assert round(new_pricing.order_total(order, user), 2) == old_checkout.checkout(order, "cash", user)["total"]
| Implementation | Random only (2,000) | With the boundary example |
|---|---|---|
| correct refactoring | pass (3.22 s) | pass (3.29 s) |
> changed to >= |
pass (bug missed) | fail: assert 450.0 == 475.0 |
The refactored pricing kept the old code's floating-point summation order on purpose: a "cleaner" sum(...) with Decimal would be better code but a behaviour change (different rounding), which belongs in a separate, deliberate commit. Refactor first with behaviour identical, then change behaviour with its own tests; mixing the two makes both unverifiable.
Experiment 4: complexity before and after
old checkout(): CCN 13 (grade C)
new line_total / order_total / member_rate: 3 / 3 / 2 (grade A)
Try it yourself
- Run the hotspot script on a repository you work on. Do the top three files match where your team feels pain?
- Compute change coupling for
requests: which pairs of files most often change in the same commit? - Refactor
should_bypass_proxiesfromrequestsinto smaller functions on a branch, with a differential test against the original. - Add a Hypothesis strategy that targets boundaries (totals near 500) instead of an explicit example, using
st.integersaround the threshold.
Revision sheet: clean code
Key ideas
- Maintainability is economics: most cost is reading and changing code.
- Names carry design: intention-revealing, domain language, consistent.
- Functions: small, one level of abstraction, few parameters, no hidden side effects; command-query separation.
- Cohesion (functional best, coincidental worst) and coupling (data < stamp < control < common < content) types.
- Modules and information hiding: hide what is likely to change behind stable interfaces.
- Errors: explicit, at the right level; don't swallow; don't use exceptions for control flow.
- Comments explain why, not what; delete commented-out code.
- Refactoring: small behaviour-preserving steps with tests green; separate from behaviour changes.
- Metrics with judgement: complexity, size, duplication, churn and hotspots point to where to look.
Numbers to remember
- Common thresholds: CCN ≤ 10 per function; functions a screen or less.
- Lab: 5.3% of
requestsfunctions had CCN > 10; top hotspot utils.py (110 commits × CCN 201). - Lab: random property testing missed a
>=boundary bug; one explicit boundary example caught it.
Pitfalls
- Refactoring and changing behaviour in one step.
- Cleaning rarely changed code while hotspots rot.
- Metric gaming (splitting functions mechanically without better names or boundaries).
- Generic names (
data,process,manager,util). - Flag parameters that make one function do two things.
- Comments that restate code and drift out of date.
Glossary
- Hotspot: complex code that changes often.
- Characterization test: captures current behaviour before changing code.
- CQS: command-query separation.
- Information hiding: modules conceal design decisions likely to change.
- Change coupling: files that tend to change together.