Refactoring Readiness Assessment
by @quochungto
Assess whether a codebase situation warrants refactoring and determine the right approach before any structural changes begin. Use this skill when a develope...
clawhub install bookforge-refactoring-readiness-assessmentπ About This Skill
name: refactoring-readiness-assessment description: "Assess whether a codebase situation warrants refactoring and determine the right approach before any structural changes begin. Use this skill when a developer is about to modify existing code and needs to decide: should I refactor first, refactor not at all, or rewrite entirely? Triggers include: developer is adding a feature and the existing code is hard to understand or extend; developer just received a bug report and suspects the code structure is hiding more bugs; a code review has surfaced design concerns and the team wants concrete guidance; code appears to have been copied more than twice in similar form; developer is unsure whether to clean up code before a deadline; codebase uses a published interface or is tightly coupled to a database schema and the developer wants to know the constraints before restructuring; developer suspects the code is so broken it cannot be stabilized without a full rewrite. This skill produces a structured go/no-go assessment and session plan β it does not apply any refactoring itself. Use code-smell-diagnosis after this skill to identify specific smells, then individual refactoring skills to apply transformations." version: 1.0.0 homepage: https://github.com/bookforge-ai/bookforge-skills/tree/main/books/refactoring/skills/refactoring-readiness-assessment metadata: {"openclaw":{"emoji":"π","homepage":"https://github.com/bookforge-ai/bookforge-skills"}} status: draft source-books: - id: refactoring title: "Refactoring: Improving the Design of Existing Code" authors: ["Martin Fowler", "Kent Beck", "John Brant", "William Opdyke", "Don Roberts"] chapters: [2, 15] tags: [refactoring, code-quality, software-design] depends-on: [] execution: tier: 1 mode: plan-only inputs: - type: description description: "User's description of the code situation: what they are trying to do (add feature, fix bug, review, clean up), what the code looks like, and any constraints (deadline, published interface, database coupling)" tools-required: [] tools-optional: [Read] mcps-required: [] environment: "Any agent environment; user supplies context in text form or answers guided questions. No code changes are made during this skill." discovery: goal: "Produce a structured refactoring readiness assessment: go/no-go decision, opportunity trigger classification, constraint inventory, Two Hats protocol plan, and session discipline rules for this specific situation" tasks: - "Identify which of the four opportunity triggers applies to the current situation" - "Check for hard blockers (non-stabilizable code, published interfaces, deadline proximity, database coupling)" - "Apply the refactor-vs-rewrite heuristic if scale of decay is uncertain" - "Determine Two Hats sequencing: which hat first, what the boundary is, how to track hat switches" - "Define session discipline rules: goal statement, step size, stop condition, backtrack trigger, pairing recommendation" - "Produce the go/no-go recommendation with rationale and next steps" audience: "Software developers, senior developers, and tech leads deciding whether and how to refactor existing code before making changes" triggers: - "Developer is about to add a feature and the code is hard to follow" - "Bug report received and code structure may be obscuring more bugs" - "Code review surfaced design concerns requiring restructuring guidance" - "Same or similar code appears in three or more places" - "Developer is unsure whether cleanup is worth the time before a deadline" - "Code may be too broken to stabilize safely for refactoring" - "Published API or database schema may constrain refactoring options"
Refactoring Readiness Assessment
When to Use
You are about to change existing code β adding a feature, fixing a bug, doing a code review, or cleaning up β and you are not sure whether to refactor first, refactor not at all, or start from scratch.
This skill runs before any code changes. It answers three questions:
1. Should we refactor? (Go / No-go) 2. If yes, what approach? (Opportunity trigger, Two Hats plan, session rules) 3. What are the risks? (Constraint inventory, stop conditions, backtrack rules)
What this skill does NOT do:
method-decomposition-refactoring, conditional-simplification-strategy, or other catalog skills for that)code-smell-diagnosis after this assessment)big-refactoring-planner for codebase-scale work)Context and Input Gathering
Required (ask if not provided)
Useful (gather if present)
Process
Step 1 β Classify the Opportunity Trigger
Why: Fowler identifies four specific situations where refactoring is most valuable. Knowing which trigger applies sets the scope and urgency of the refactoring session. Refactoring without a trigger is speculative and hard to time-box.
Identify which trigger best matches the user's situation:
Trigger A: Rule of Three (Don Roberts) The same or structurally similar logic appears in three or more places. The third occurrence is the signal to refactor β not the first (do it), not the second (wince but proceed), but the third.
Trigger B: Refactor When Adding a Feature The code is hard to understand or extend for the planned addition. Refactoring first makes the feature addition faster, not slower β once the code is well-structured, adding the feature is straightforward.
Trigger C: Refactor When Fixing a Bug A bug report is a sign that code was not clear enough to reveal the bug during development. Refactoring to understand the code often exposes the bug itself, and the improved structure prevents similar bugs.
Trigger D: Refactor During Code Review Code review is the ideal moment to suggest structural improvements while the author is present and the code is being read fresh. Implementing suggestions in the review session (small review groups) creates more concrete outcomes than suggestions alone.
Record the trigger classification. If more than one applies, use the primary motivation for this session.
Step 2 β Check Hard Blockers
Why: Some situations make refactoring unsafe, premature, or impossible to complete successfully. Proceeding into these situations without acknowledging the constraints leads to half-finished refactorings that leave the code worse than before.
Run through each blocker category:
Blocker 1: Non-stabilizable code (rewrite candidate) The code does not work correctly and cannot be made to work mostly correctly before refactoring.
Blocker 2: Deadline proximity A release, deployment, or hard commitment is within a few days.
Blocker 3: Published interfaces The code exposes methods or APIs that external code depends on and that you cannot find and change everywhere.
Blocker 4: Database schema coupling The code is tightly coupled to a relational database schema, and refactoring the object model would require a data migration.
If one or more hard blockers are present, the assessment may be a partial go (proceed with constraints explicitly stated) or a no-go.
Step 3 β Apply the Refactor-vs-Rewrite Heuristic
Why: Fowler is explicit that sometimes the right answer is to start over rather than refactor. But "this is a mess" is not a sufficient reason to rewrite β rewrites have their own risks, and partial rewrites that decompose by component are often better than full rewrites.
Apply this heuristic only if Blocker 1 (non-stabilizable code) triggered or if the code appears fundamentally broken:
Signal that rewrite is warranted:
Fowler's compromise route: Do not rewrite the whole system. Decompose it into components with strong encapsulation. Evaluate the refactor-vs-rewrite decision one component at a time. A component that is too broken to stabilize can be rewritten. Components that are poorly structured but functional can be refactored.
Output of Step 3:
If no blockers from Step 2 triggered and the code works, skip this step.
Step 4 β Define the Two Hats Protocol
Why: Kent Beck's Two Hats metaphor captures the most common refactoring failure mode: developers mix structural cleanup with feature additions or bug fixes, losing track of which changes do what. When a test fails during mixed-hat work, it is impossible to know whether the refactoring broke something or the feature change introduced a bug. Keeping the hats separate preserves this diagnostic clarity.
The Two Hats:
Rules: 1. You wear exactly one hat at a time. Never both simultaneously. 2. When you realize you need to switch hats, finish your current step, verify tests pass, then switch. 3. Keep a list of hat-switch requests β things you notice that need doing in the other hat. Do not act on them immediately. Act on them when you switch hats.
For this session, determine:
Step 5 β Define Session Discipline
Why: Kent Beck's session rules from Chapter 15 are the most commonly skipped part of refactoring practice and the source of most refactoring failures. Without them, developers refactor for too long without testing, get lost, cannot find the source of a test failure, and abandon the session mid-stream β leaving the code in a worse state than when they started. The rules are designed to make stopping and backtracking safe rather than shameful.
Define these five rules for this specific session:
Rule 1: Pick a goal State the refactoring goal in one sentence before touching the code. "I am refactoring to [specific outcome] so that [specific next task] becomes possible."
Rule 2: Move in small steps Each step is the smallest transformation that leaves the code in a consistent, passing state. Run tests after each step β not after every three steps, not at the end.
Rule 3: Stop when unsure If you cannot prove to yourself that the current step preserves behavior, stop. Do not proceed.
Rule 4: Backtrack to last passing state If a test fails and you are not certain which change caused it: do not debug. Backtrack.
Rule 5: Work in pairs (recommended) Pair programming provides three benefits specific to refactoring: it keeps step sizes small (partner observes drift), it provides a second opinion on when to stop, and it provides quiet confidence when you are uncertain. Your partner catches the moment you switch from confident steps to uncertain ones.
Step 6 β Produce the Assessment Output
Why: The assessment must be tangible and actionable. A verbal judgment ("yeah, refactor it") is not sufficient. The output is a document the developer can refer to during the session β especially the hat-switch boundary and the backtrack rule, which are hardest to remember under pressure.
Write the assessment in this structure:
REFACTORING READINESS ASSESSMENT
Situation: [One sentence describing the code and the immediate task]
Opportunity Trigger: [A / B / C / D] β [name and brief rationale]
Go / No-Go Recommendation: [Go / No-Go / Conditional Go] [2-3 sentences explaining the recommendation]
Constraint Inventory:
Refactor vs. Rewrite:
Two Hats Plan:
Session Discipline Rules:
Next Steps: 1. [First concrete action: e.g., "Add tests for OrderProcessor.process() to establish baseline"] 2. [Second action: e.g., "Run code-smell-diagnosis on OrderProcessor to identify which smells to address"] 3. [Third action: e.g., "Apply method-decomposition-refactoring to extract fee calculation"]
Key Principles
Refactoring is not a scheduled activity. Fowler is explicit: do not allocate two weeks every few months to refactoring. Refactoring happens in small bursts, triggered by real tasks. You refactor because you want to do something else, and refactoring helps you do that other thing.
The code must work before you refactor. Refactoring restructures working code. Code that does not work mostly correctly cannot be safely transformed β every refactoring step's safety depends on tests that confirm behavior is preserved.
Design debt accrues interest. Ward Cunningham's framing: unfinished refactoring is debt. Some debt is necessary to function. But the interest payment is the extra cost of maintenance and slow development caused by overly complex code. When the payments become too great, you are overwhelmed.
Not having enough time to refactor is a sign you need to refactor. Tight schedules that prevent cleanup cause the conditions that make schedules tight. If you never have time to clean up, you are paying the interest on accumulated design debt.
A big refactoring is a recipe for disaster. Beck's warning from Chapter 15 is direct: when you see all the problems at once and want to clean up everything in sight, resist. Nibble at the problem β take a few minutes to clean up an area when you are about to add functionality there. A three-month cleanup halt is not acceptable to any organization and they are right to refuse it.
Examples
Example A: Feature Addition (Trigger B)
Situation: Adding promotional pricing to OrderProcessor. The method is 200 lines long, mixes fee calculation, tax computation, and discount application in a single block.
Assessment:
Example B: Bug Fix (Trigger C)
Situation: Bug report: "discounts not applying correctly for international orders." Code mixes currency handling with discount logic in several places.
Assessment:
Example C: Rewrite Candidate
Situation: Legacy billing module. Known to produce incorrect results in certain scenarios. Cannot write tests that pass because the existing behavior is wrong.
Assessment:
Example D: Deadline Proximity (No-Go)
Situation: Release is tomorrow. Developer wants to clean up the authentication module because it has been bothering them.
Assessment:
References
references/two-hats-protocol.md β Extended Two Hats guidance including hat-switch request tracking templates and pair programming patterns for refactoring sessionsreferences/refactoring-constraints.md β Detailed guidance on published interface migration strategies, database schema isolation layers, and design debt managementLicense
This skill is licensed under CC-BY-SA-4.0. Source: BookForge β Refactoring: Improving the Design of Existing Code by Martin Fowler with Kent Beck, John Brant, William Opdyke, and Don Roberts.
Related BookForge Skills
Install related skills from ClawhHub:
clawhub install bookforge-code-smell-diagnosisclawhub install bookforge-method-decomposition-refactoringclawhub install bookforge-big-refactoring-plannerclawhub install bookforge-build-refactoring-test-suiteOr install the full book set from GitHub: bookforge-skills
β‘ When to Use
π‘ Examples
Example A: Feature Addition (Trigger B)
Situation: Adding promotional pricing to OrderProcessor. The method is 200 lines long, mixes fee calculation, tax computation, and discount application in a single block.
Assessment:
Example B: Bug Fix (Trigger C)
Situation: Bug report: "discounts not applying correctly for international orders." Code mixes currency handling with discount logic in several places.
Assessment:
Example C: Rewrite Candidate
Situation: Legacy billing module. Known to produce incorrect results in certain scenarios. Cannot write tests that pass because the existing behavior is wrong.
Assessment:
Example D: Deadline Proximity (No-Go)
Situation: Release is tomorrow. Developer wants to clean up the authentication module because it has been bothering them.
Assessment: