Catalogue / readable-code-refactoring
readable-code-refactoring
Older skill: source not recordedSignedCoaches code-quality review and behavior-preserving refactoring, covering intention-revealing names, small single-purpose functions, disciplined comments, error handling, unit-test hygiene, the SOLID design principles, and code-smell diagnosis with matching fixes. Use when reviewing or improving exi…--- name: readable-code-refactoring description: > Coaches code-quality review and behavior-preserving refactoring, covering intention-revealing names, small single-purpose functions, disciplined comments, error handling, unit-test hygiene, the SOLID design principles, and code-smell diagnosis with matching fixes. Use when reviewing or improving existing code, choosing or renaming identifiers, restructuring functions or classes, applying SOLID, hunting code smells, or writing unit tests. Not for choosing frameworks or libraries, configuring linters, formatters or CI, or performance tuning. ---
Readable Code and Refactoring
Use this skill whenever you are asked to review, clean up, or restructure code. Everything here is language-agnostic; the examples are pseudocode, so translate the ideas into the idioms of the language in front of you.
Review workflow
Work through these steps in order:
- Restate the code's job. Before changing a line, say back in one or two sentences what the module does and who calls it. If you cannot, that confusion is itself the first finding.
- Build a safety net. Locate the tests and run them. If the code you are about to touch has no tests, write a few characterization tests first that pin down today's observable behavior.
- List the smells using the catalog below, ranked by impact: bugs, misleading names, and wrong-looking logic outrank style nits.
- Fix in small, behavior-preserving steps. One rename or one extraction at a time, re-running the tests between steps.
- Report what you changed and why, and name anything you deliberately left alone.
The reasoning behind this order: a tidy-up that alters behavior is not a tidy-up, it is an unreviewed feature change smuggled in under a cleaning label.
Naming
A name is the cheapest documentation you will ever write. Apply these rules:
- The name must say what the value holds and why it exists:
minutesSinceLastVisit, notmordur. - Never encode a wrong type hint: if
membersis keyed by email, call itmembersByEmail. - Distinct names must be genuinely distinct:
Invoice,InvoiceDraft, andInvoiceSummarycarry meaning;InvoiceDataandInvoiceInfodo not. - Keep names pronounceable and searchable. Reserve single letters for tight loop counters.
- Drop scope or type prefixes such as member markers and type abbreviations; the tools know the type already.
- Classes are nouns, functions are verb phrases, and booleans read as questions:
isEligible,hasOverdueFine,canRenew. - Give literals a name:
LATE_FEE_GRACE_DAYS = 3beats a bare3six lines deep. - If a function does more than its name admits, split or rename rather than documenting the surprise.
// before
function f(w, n) {
return w * n * 1.5
}
// after
HEAVY_ITEM_MULTIPLIER = 1.5
function surchargeFor(totalWeightKg, heavyItemCount) {
return totalWeightKg * heavyItemCount * HEAVY_ITEM_MULTIPLIER
}Function design
Hold every function to these standards:
- Small. Roughly 15–25 lines is the comfortable ceiling; longer usually means mixed steps.
- One job. The test: can you describe it without the word "and"? Can you extract a helper whose name is not a restatement of the original?
- One abstraction level. A function that parses a document should not also be splitting raw strings; push the low-level parts into helpers.
- Few parameters. Zero is ideal, one or two fine, three questionable, four or more means grouping.
placeHold(memberId, isbn, branchId, days, notify)becomesplaceHold(request)with aHoldRequestobject. - No boolean flags. A flag means two functions wearing one coat:
refreshCache(true)should berefreshCacheForcefully(). - No hidden side effects. A query named
isSeatHeldmust not also send a reminder email. - Commands separate from queries. Split
setAndFetchExpiryinto a setter and a getter. - Error handling in its own shell. Keep the try/catch thin and delegate the happy path to an inner function.
Aim for the stepdown shape, where each function is followed by the helpers it names, so the file reads top to bottom like an outline:
function admitVisitor(visitor) {
verifyTicket(visitor)
seat = findFreeSeat(visitor.zone)
markSeatOccupied(seat, visitor)
printBadge(visitor, seat)
}Comment policy
Treat a comment as a confession that the code could not speak for itself, and try harder code first — rename, extract a helper, or name a constant. Reach for a comment only when it adds something code cannot:
- The *why* behind a non-obvious choice, such as keeping a linear search because the list is nearly always under ten items.
- A warning about consequences: this test sleeps two minutes, this function must not run against live data.
- A clarification of third-party behavior you cannot change.
- A tracked TODO with a ticket reference, and public API documentation.
Delete or refuse to write these: restatements of the adjacent line, changelog journals inside functions, bylines, banner separators, and commented-out code. Version control keeps history so the file does not have to. One exception: if a comment is the only surviving specification of tricky behavior, ask the user before removing it.
Layout and formatting
Formatting is a team signal, not a personal statement:
- If the repository has a formatter or style config, defer to it entirely and spend your effort elsewhere.
- Keep files scannable; a few hundred lines is fine, four digits is a smell.
- Open each file with the high-level entry points and let the detail sink to the bottom, so a reader gets the synopsis first.
- Separate distinct thoughts with a blank line, keep related lines adjacent, declare variables near their first use, and place callers above their callees.
- Keep lines short enough to avoid horizontal scrolling, one statement per line, and do not collapse even short blocks onto a single line.
- Skip column-alignment games; they create noise in diffs.
Handling failures
Error handling should sit beside the logic, not woven through it:
- Prefer exceptions over returned status codes, which force callers into nested checks.
- When writing risky code, sketch the try/catch/finally skeleton first, then fill the happy path.
- Attach context to every throw — which identifier, which stage:
DeliveryNotFoundException(trackingCode), never a generic "failed". - Group exception types by how callers will react, not by where they originated.
- Never return null from a lookup; throw, return an Optional/Maybe style value, or hand back an empty collection for list-shaped results.
- Do not accept null arguments either: validate, assert, or use non-nullable types.
- Replace scattered special-case checks with an object: an
UnregisteredGuestwhosediscountRate()returns zero removes null branches from every caller.
Testing habits
Hold test code to the same quality bar as production code:
- Fast, Independent, Repeatable, Self-validating, Timely. Slow tests get skipped, order-dependent tests mislead, and tests that depend on the wall clock or network lie.
- One concept per test, with a name that states the behavior:
renew_membership_expiredCard_declinesAndKeepsStatus. - Lay each test out as Arrange, Act, Assert with blank lines between the phases.
- Inject time and randomness: a
FakeClockpinned to 2025-03-02 makesisOverduedeterministic. - Know your doubles: a stub returns canned answers, a spy records calls, a mock verifies interactions, a fake is a lightweight working implementation such as an in-memory store.
- Treat coverage numbers as a flashlight for gaps, never as the goal.
SOLID at a glance
| Principle | Rule of thumb | Tell-tale violation | |---|---|---| | Single Responsibility | One reason to change per module | The class description needs "and" | | Open/Closed | Extend by adding code, not editing it | Each new variant forces edits to one switch | | Liskov Substitution | Subtypes honor the parent's contract | A subtype throws or no-ops an inherited method | | Interface Segregation | Narrow, role-based interfaces | Implementers stub out methods they do not support | | Dependency Inversion | Depend on abstractions | Business logic constructs its own infrastructure |
Single Responsibility. A Loan class that computes interest, writes to the database, and prints statements changes when finance rules change, when the schema changes, and when the layout changes. Split it into Loan, InterestCalculator, LoanRepository, and StatementPrinter so each group of stakeholders touches its own file.
Open/Closed. A fareFor(route) method switching on bus, tram, and ferry must be edited for every new vehicle. Replace the switch with a FarePolicy interface, one implementation per vehicle; adding CableCarFare then touches nothing that already works.
Liskov Substitution. If Playback.seek() exists but LiveStreamPlayback.seek() throws, every caller of the base type is a latent crash. Split out a Seekable interface so each type only promises what it keeps. Likewise, a subclass may not quietly tighten a parent's rules — a junior account that suddenly rejects withdrawals the base account permits breaks its callers.
Interface Segregation. A fat Notifier with email, SMS, broadcast scheduling, and webhook registration forces an SMS-only implementation to stub three methods. Split into role interfaces such as EmailSender, SmsSender, and Broadcaster, and let each class implement only what it truly supports.
Dependency Inversion. A report class that opens a database connection and constructs a CSV exporter internally cannot be tested or swapped. Pass in ReportStore and ReportExporter interfaces through the constructor — preferably constructor injection — wire the real implementations once at startup, and hand tests in-memory fakes. Treat clock, randomness, filesystem, network, and external services as dependencies worth injecting.
Smell catalog
When you spot one of these, apply the matching fix:
| Smell | What you see | Usual fix | |---|---|---| | Long function | Screens of mixed steps | Extract step helpers | | Duplicated logic | Same validation copy-pasted | Extract one shared helper | | God object | One class answers every need | Split by responsibility | | Long parameter list | Four-plus arguments | Introduce a parameter object | | Data clump | The same trio travels together | Extract a value type | | Primitive obsession | Strings and floats posing as emails and money | Small validated value objects | | Feature envy | Method mostly reads another class's data | Move it to that class | | Message chain | Call chains walking through strangers | Hide the delegate | | Flag argument | A boolean flips behavior | Two named functions | | Type-code switch | Conditionals keyed on a type field | Polymorphism | | Speculative generality | Abstractions nobody uses | Collapse them | | Dead code | Unreachable or commented-out blocks | Delete | | Lying name or comment | Says one thing, code does another | Rename or repair | | Magic number | Unexplained literal | Named constant | | Inconsistent twins | The same task done two ways | Pick one, everywhere | | Buried config | Tunables hidden deep in logic | Hoist to one visible place | | Hidden temporal coupling | Must call init first, undocumented | Construct ready-to-use objects | | Skipped tests | Ignored or disabled tests lingering | Fix or remove, with the user aware |
Tidy as you go
Every file you touch should come out slightly tidier than you found it: one rename, one extraction, one dead block deleted. Small visits compound — one improvement per working day is several hundred per year. Bound the habit:
- Time-box the tidying to about a quarter of an hour; anything larger becomes its own task for the user to schedule.
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 13.5 kB | bf2dfacd6621 |
| examples.json | 2.1 kB | d542e9ddb273 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 6 Oct 2026 |
Locking a skill to one version needs Pro.