Refactoring
Purpose
Improve the internal structure of code without changing observable behavior. The skill
covers the four moves that matter most in enterprise codebases: eliminating dead and
duplicate code, tightening cohesion, restoring readability (ordering, guard clauses,
named conditions), and optimizing functions — each verified by tests and tooling.
When to Use / When NOT to Use
Use when:
- Someone asks to "refactor", "clean up", "remove dead code", "declutter", or
"optimize this function" while behavior must stay identical.
- A module has grown mixed responsibilities, orphaned helpers, or unreadable nesting.
- A library migration (upgrade or replacement) must preserve its public contract.
Do NOT use when:
- Behavior is allowed to change — that is feature work; plan it as such.
- The problem is missing tests entirely; stabilize with
testing/unit-testing first.
- You only need style fixes the linter can apply — use
static-analysis.
Prerequisites & Assumptions
- A green test suite exists before the first change; if not, write
characterization tests per
testing/unit-testing.
- Language rules for Go, Java, or Python come from
language-specific/*.
- No behavior change, no public-signature change, no dependency additions without
explicit approval.
Step-by-Step Workflow
- Pin behavior — run the full test suite and record results; add tests for any
untested behavior you are about to touch.
- Audit — build a caller/callee map of the target scope and produce two tables:
dead-code candidates (categories below) and cohesion violations (dimensions below).
- Order the work — smallest, safest changes first: dead code → duplicates →
cohesion moves → readability → performance. One concern per commit
(see
git-workflow for commit hygiene).
- Execute in steps — after every step re-run tests; never stack unverified moves.
- Optimize last — only with a benchmark before/after (
performance owns the
method); optimization without measurement is out of scope here.
- Report — deliver the audit tables, the list of behavior checks performed, and
confirmation that exported APIs are unchanged (or list approved exceptions).
Dead-code categories and protections
| Category |
Example |
Rule |
| Unreachable |
Code after an unconditional return |
Delete |
| Orphaned |
Function with zero callers in repo and tests |
Delete |
| Superseded |
parseV1 kept after parseV2 shipped |
Delete |
| Redundant condition |
Check provably always false/true |
Delete |
| Commented-out code |
// result = legacyProcess(x) |
Delete — Git history is the archive |
| Dead constant/variable |
Never read |
Delete |
| Exported symbol, external callers unknown |
Any public API item |
Mark SUSPECTED_DEAD, do NOT delete — needs human confirmation |
| Test-only helper |
Used only by _test.go / test fixtures |
Keep, mark as intentional |
| Interface no-op stub |
func (n *nopLogger) Log(...) {} |
Keep, mark "no-op: satisfies " |
Cohesion dimensions (audit each file against these)
| Dimension |
Question |
Red flag |
| Functional |
One responsibility per file? |
Parsing + I/O + business rules mixed |
| Sequential |
Clear pipeline of dependent steps? |
Steps invoked from unrelated places |
| Communicational |
Code operating on the same data co-located? |
One struct mutated from 3+ files |
| Logical |
Same-category functions grouped? |
Validators scattered everywhere |
| Temporal |
Lifecycle-adjacent calls grouped? |
Init split across init() and distant constructors |
Readability standards applied during the refactor
- Guard clauses: validate and return early; the happy path is the last, unindented
block. Nesting deeper than 2 levels is a finding.
- Named conditions: extract multi-part booleans into well-named variables.
- Step comments: functions longer than ~40 lines get phase comments explaining why,
not what. Comments that restate the code are deleted, not rewritten.
- Declaration ordering (per file): package doc → imports (stdlib, external, internal)
→ constants/vars → types → constructors → primary exported API → interface
implementations (grouped, marked
// --- Implements <Interface> ---) → secondary
helpers → getters/setters (alphabetical) → unexported helpers (most-called first).
- Reuse before rewrite: search the codebase for an existing helper before writing a
new one; duplicating an existing validation or conversion is a finding.
- Style alignment: the refactor must match the surrounding code's conventions —
naming, error handling, receiver style — not introduce a second style.
Legacy convention, opt-in
Some teams (the convention is preserved here from the legacy repository) consolidate Go
packages into constant.go / type.go / errors.go / options.go / utilities.go
with unexported fields, FieldName() getters, SetFieldName() setters, and With*
functional options. If the target repo adopts it, apply it consistently; otherwise
follow the idiomatic layout of the existing codebase. Do not mix the two styles in one
package.
Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)
- MUST keep every refactor behavior-preserving; observable outputs, error types, and
public signatures stay identical unless an approved contract change is documented.
- MUST run tests after every step; a step is not done until green.
- MUST mark externally-visible dead code
SUSPECTED_DEAD instead of deleting it.
- MUST delete commented-out code rather than "temporarily" keeping it.
- SHOULD split refactoring from feature work into separate changes; mixing them
hides risk.
- SHOULD cap a single refactor PR at ~400 changed lines; split larger moves.
- MUST NOT rename or reorder exported identifiers as a side effect — that is an API
change and needs its own review under
api-design rules.
- MUST NOT introduce new dependencies during a refactor.
Examples
Good — guard clauses and a named condition (Go):
func (d *Diagram) compile() ([]byte, error) {
// Step 1: reject empty diagrams — the DOT renderer panics on them.
if len(d.nodes) == 0 {
return nil, ErrEmptyDiagram
}
// Step 2: sort deterministically so snapshot tests are reproducible.
sorted := d.sortedNodes()
adj := buildAdjacency(sorted, d.edges)
return d.renderer.Render(adj)
}
Bad — nesting hides the happy path:
func process(input string) (string, error) {
if input != "" {
if len(input) < 256 {
result, err := transform(input)
if err == nil {
return result, nil
}
}
}
return "", ErrInvalidInput
}
Why it fails: three nesting levels to reach the happy path, one error value for three
different failures, and no context in the error.
Checklist
Common Pitfalls
- Big-bang refactors — weeks-long branches that never merge; keep steps shippable.
- Silent behavior drift — "just cleaning up" that changes an error message a client
matches on; treat messages and types as observable behavior.
- Refactor-as-cover — smuggling feature changes into a refactor PR; reviewers must
reject mixed changes.
- Deleting exported code — an unused exported symbol in a library may have external
callers; only
SUSPECTED_DEAD marking is safe.
References
1---2name: refactoring3description: 'Plans and executes behavior-preserving refactors — dead-code removal, cohesion tightening, declaration ordering, encapsulation, and function optimization. Trigger with "refactor this package", "remove dead code", or "make this function readable".'4metadata:5 source: https://skillmd.com/skills/pnguyen215/refactoring6---78# Refactoring910## Purpose1112Improve the internal structure of code without changing observable behavior. The skill13covers the four moves that matter most in enterprise codebases: eliminating dead and14duplicate code, tightening cohesion, restoring readability (ordering, guard clauses,15named conditions), and optimizing functions — each verified by tests and tooling.1617## When to Use / When NOT to Use1819Use when:2021- Someone asks to "refactor", "clean up", "remove dead code", "declutter", or22 "optimize this function" while behavior must stay identical.23- A module has grown mixed responsibilities, orphaned helpers, or unreadable nesting.24- A library migration (upgrade or replacement) must preserve its public contract.2526Do NOT use when:2728- Behavior is allowed to change — that is feature work; plan it as such.29- The problem is missing tests entirely; stabilize with `testing/unit-testing` first.30- You only need style fixes the linter can apply — use `static-analysis`.3132## Prerequisites & Assumptions3334- A green test suite exists before the first change; if not, write35 characterization tests per `testing/unit-testing`.36- Language rules for Go, Java, or Python come from `language-specific/*`.37- No behavior change, no public-signature change, no dependency additions without38 explicit approval.3940## Step-by-Step Workflow41421. **Pin behavior** — run the full test suite and record results; add tests for any43 untested behavior you are about to touch.442. **Audit** — build a caller/callee map of the target scope and produce two tables:45 dead-code candidates (categories below) and cohesion violations (dimensions below).463. **Order the work** — smallest, safest changes first: dead code → duplicates →47 cohesion moves → readability → performance. One concern per commit48 (see `git-workflow` for commit hygiene).494. **Execute in steps** — after every step re-run tests; never stack unverified moves.505. **Optimize last** — only with a benchmark before/after (`performance` owns the51 method); optimization without measurement is out of scope here.526. **Report** — deliver the audit tables, the list of behavior checks performed, and53 confirmation that exported APIs are unchanged (or list approved exceptions).5455### Dead-code categories and protections5657| Category | Example | Rule |58| ----------------------------------------- | -------------------------------------------- | --------------------------------------------------------------- |59| Unreachable | Code after an unconditional `return` | Delete |60| Orphaned | Function with zero callers in repo and tests | Delete |61| Superseded | `parseV1` kept after `parseV2` shipped | Delete |62| Redundant condition | Check provably always false/true | Delete |63| Commented-out code | `// result = legacyProcess(x)` | Delete — Git history is the archive |64| Dead constant/variable | Never read | Delete |65| Exported symbol, external callers unknown | Any public API item | Mark `SUSPECTED_DEAD`, do NOT delete — needs human confirmation |66| Test-only helper | Used only by `_test.go` / test fixtures | Keep, mark as intentional |67| Interface no-op stub | `func (n *nopLogger) Log(...) {}` | Keep, mark "no-op: satisfies <Interface>" |6869### Cohesion dimensions (audit each file against these)7071| Dimension | Question | Red flag |72| --------------- | ------------------------------------------- | --------------------------------------------------- |73| Functional | One responsibility per file? | Parsing + I/O + business rules mixed |74| Sequential | Clear pipeline of dependent steps? | Steps invoked from unrelated places |75| Communicational | Code operating on the same data co-located? | One struct mutated from 3+ files |76| Logical | Same-category functions grouped? | Validators scattered everywhere |77| Temporal | Lifecycle-adjacent calls grouped? | Init split across `init()` and distant constructors |7879### Readability standards applied during the refactor8081- **Guard clauses**: validate and return early; the happy path is the last, unindented82 block. Nesting deeper than 2 levels is a finding.83- **Named conditions**: extract multi-part booleans into well-named variables.84- **Step comments**: functions longer than ~40 lines get phase comments explaining why,85 not what. Comments that restate the code are deleted, not rewritten.86- **Declaration ordering** (per file): package doc → imports (stdlib, external, internal)87 → constants/vars → types → constructors → primary exported API → interface88 implementations (grouped, marked `// --- Implements <Interface> ---`) → secondary89 helpers → getters/setters (alphabetical) → unexported helpers (most-called first).90- **Reuse before rewrite**: search the codebase for an existing helper before writing a91 new one; duplicating an existing validation or conversion is a finding.92- **Style alignment**: the refactor must match the surrounding code's conventions —93 naming, error handling, receiver style — not introduce a second style.9495### Legacy convention, opt-in9697Some teams (the convention is preserved here from the legacy repository) consolidate Go98packages into `constant.go` / `type.go` / `errors.go` / `options.go` / `utilities.go`99with unexported fields, `FieldName()` getters, `SetFieldName()` setters, and `With*`100functional options. If the target repo adopts it, apply it consistently; otherwise101follow the idiomatic layout of the existing codebase. Do not mix the two styles in one102package.103104## Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)105106- **MUST** keep every refactor behavior-preserving; observable outputs, error types, and107 public signatures stay identical unless an approved contract change is documented.108- **MUST** run tests after every step; a step is not done until green.109- **MUST** mark externally-visible dead code `SUSPECTED_DEAD` instead of deleting it.110- **MUST** delete commented-out code rather than "temporarily" keeping it.111- **SHOULD** split refactoring from feature work into separate changes; mixing them112 hides risk.113- **SHOULD** cap a single refactor PR at ~400 changed lines; split larger moves.114- **MUST NOT** rename or reorder exported identifiers as a side effect — that is an API115 change and needs its own review under `api-design` rules.116- **MUST NOT** introduce new dependencies during a refactor.117118## Examples119120Good — guard clauses and a named condition (Go):121122```go123func (d *Diagram) compile() ([]byte, error) {124 // Step 1: reject empty diagrams — the DOT renderer panics on them.125 if len(d.nodes) == 0 {126 return nil, ErrEmptyDiagram127 }128 // Step 2: sort deterministically so snapshot tests are reproducible.129 sorted := d.sortedNodes()130 adj := buildAdjacency(sorted, d.edges)131 return d.renderer.Render(adj)132}133```134135Bad — nesting hides the happy path:136137```go138func process(input string) (string, error) {139 if input != "" {140 if len(input) < 256 {141 result, err := transform(input)142 if err == nil {143 return result, nil144 }145 }146 }147 return "", ErrInvalidInput148}149```150151Why it fails: three nesting levels to reach the happy path, one error value for three152different failures, and no context in the error.153154## Checklist155156- [ ] Tests green before starting; characterization tests added for untested logic.157- [ ] Dead-code audit table produced, with `SUSPECTED_DEAD` marks where needed.158- [ ] Cohesion audit table produced with corrective actions.159- [ ] Each commit is behavior-preserving and single-purpose.160- [ ] Public API surface unchanged (verified by diffing exported symbols).161- [ ] Benchmarks run before/after for any performance-targeted change (`performance`).162- [ ] No new dependencies, no placeholder comments, no commented-out code left behind.163164## Common Pitfalls165166- **Big-bang refactors** — weeks-long branches that never merge; keep steps shippable.167- **Silent behavior drift** — "just cleaning up" that changes an error message a client168 matches on; treat messages and types as observable behavior.169- **Refactor-as-cover** — smuggling feature changes into a refactor PR; reviewers must170 reject mixed changes.171- **Deleting exported code** — an unused exported symbol in a library may have external172 callers; only `SUSPECTED_DEAD` marking is safe.173174## References175176- Fowler, _Refactoring_ (2nd ed.): https://martinfowler.com/books/refactoring.html177- Effective Go — reuse, composition, naming: https://go.dev/doc/effective_go178- Google Engineering Practices — code review: https://google.github.io/eng-practices/review/