OBEY Refactoring by Martin Fowler
Purpose
This repository follows the discipline of Refactoring in the sense of Martin Fowler:
improve the internal structure of code without changing its observable behavior.
All code generation, edits, and reviews must optimize for:
- small behavior-preserving changes
- clearer names and simpler control flow
- lower duplication
- smaller units of responsibility
- explicit movement from bad design toward good design
- steady design improvement as part of daily work
This file is a binding engineering policy: MUST is binding, SHOULD is a strong default, and MUST NOT is forbidden.
Primary Directive
When modifying existing code, do not start by rewriting large areas.
Start by making the next safe structural improvement that makes the desired change easier.
Prefer:
- establish a safety net
- make a preparatory refactoring
- make the functional change
- refactor again if needed
Reject changes that bundle large functional changes with unrelated structural churn.
What Counts as Refactoring
Refactoring here means:
- changing structure without changing external behavior
- applying small, composable transformations
- removing code smells before or during feature work
- making the next change easier
- improving readability, locality, and testability
Refactoring here does not mean:
- large rewrites
- unverified cleanup
- “modernization” with unclear behavioral impact
- renaming everything at once
- mixing architecture migration, feature work, and cleanup in one uncontrolled patch
Non-Negotiable Rules
Preserve Behavior
- Refactorings must preserve observable behavior.
- If behavior must change, isolate the behavior change from structural refactoring.
- Never disguise a feature change as a refactoring.
Work in Small Steps
- Prefer many small safe edits over one large transformation.
- Each step should be understandable and reversible.
- If a patch feels too large to reason about locally, split it.
Keep the System Running
- Do not leave code in a broken intermediate state unless explicitly asked for a draft.
- Every refactoring sequence should maintain a runnable, buildable state where practical.
Refactor Before and After Feature Work
- If code is hard to change, first reshape it.
- After the feature lands, clean remaining structural debt introduced by the change.
Use the Simplest Helpful Refactoring
- Do not introduce patterns or abstractions earlier than needed.
- Prefer local simplification before large-scale abstraction.
Safety Rules
Tests and Verification
- Create or identify a safety net before risky refactoring.
- Prefer characterization tests when working on unclear existing behavior.
- If tests are absent, make the smallest changes possible and improve testability first.
- Keep refactoring and test updates aligned with preserved behavior.
- Never delete a failing test just to complete a refactoring.
Commit and Patch Discipline
- Separate structural edits from behavior changes whenever practical.
- Group related refactorings together.
- Avoid giant mixed commits that rename, move, redesign, and change logic all at once.
- Prefer reviewable sequences of transformations.
Preparatory Refactoring
Before implementing a feature, ask:
- what makes this change awkward?
- what local structural change would make it straightforward?
- can I rename, extract, move, split, or inline first?
Do the preparatory refactoring before the feature change.
Code Smell Policy
When modifying code, actively look for these smells.
Duplicated Code
- Duplicate logic is a default target for elimination.
- Remove duplication by extracting shared behavior, not by introducing vague utility dumping grounds.
- Do not abstract coincidental similarity.
Long Functions
- Split long functions when they mix responsibilities, levels of abstraction, or phases of work.
- Extract meaningful chunks with names that explain intent.
- Do not create micro-method noise with no explanatory value.
Long Parameter Lists
- Replace repeated clumps with parameter objects or richer domain objects where appropriate.
- Remove boolean flags that switch behavior.
- Avoid signatures that require callers to memorize argument order.
Global Data and Hidden Dependencies
- Reduce reliance on globals, singletons, and ambient context.
- Make dependencies explicit where possible.
- Refactor toward injection, parameters, or clear ownership.
Divergent Change
- If one class changes for many different reasons, split responsibilities.
- Separate business logic, formatting, transport, persistence, and integration concerns.
Shotgun Surgery
- If one change forces edits across many files, centralize the knowledge.
- Introduce a better boundary or clearer ownership.
Feature Envy
- If a method mostly manipulates another object's data, move it or reshape the model.
- Put behavior near the data or concept it belongs to.
Data Clumps and Primitive Obsession
- Replace repeated primitive bundles with meaningful types.
- Give recurring business concepts names and validation.
Switch Statements and Conditionals
- Reduce repeated branching on type or mode when polymorphism, tables, strategies, or better data structures fit.
- Do not replace a single honest conditional with needless indirection.
Temporary Fields and Weird Lifecycles
- Remove fields that exist only for unusual code paths when a separate object or clearer phase model is better.
- Prefer modeling states explicitly over half-initialized objects.
Middle Man and Speculative Generality
- Remove forwarding layers that add no value.
- Delete abstractions created “just in case” if they are not earning their keep.
Preferred Refactoring Moves
Naming Refactorings
- Rename variables to reveal intent.
- Rename functions to describe behavior, not mechanism.
- Rename types and modules to align with problem-domain terminology.
- Rename before deeper refactoring when bad names block understanding.
Extraction Refactorings
- Extract function when a block has a coherent purpose.
- Extract variable when an expression is hard to read.
- Extract class when one class has multiple reasons to change.
- Extract module when a file mixes unrelated concerns.
Movement Refactorings
- Move function to the module or type where the data or concept lives.
- Move field when ownership is clearer elsewhere.
- Move statements to group related operations and reduce cognitive jumps.
Simplification Refactorings
- Inline accidental abstractions.
- Collapse unnecessary layers.
- Replace nested conditionals with guard clauses where it improves clarity.
- Consolidate duplicate conditional fragments.
Data Refactorings
- Encapsulate mutable state.
- Replace magic values with named constants or domain types.
- Introduce parameter objects for repeated argument groups.
- Replace raw collections with named abstractions when behavior accumulates around them.
Refactoring Catalog Index
Composing Methods
- USE Extract Method when a code fragment has a coherent purpose and a useful name.
- USE Inline Method when a method body is clearer than its indirection.
- USE Inline Temp when a temporary variable obscures a direct expression.
- USE Replace Temp with Query when a calculated value deserves a named query and can be reused safely.
- USE Introduce Explaining Variable when a complex expression needs named parts.
- USE Split Temporary Variable when one variable carries multiple meanings.
- USE Remove Assignments to Parameters when parameter mutation obscures input meaning.
- USE Replace Method with Method Object when local state prevents clean extraction.
- USE Substitute Algorithm when a clearer algorithm can replace a tangled one without changing behavior.
Moving Features
- USE Move Method or Move Field when behavior or state belongs more naturally to another object.
- USE Extract Class when one class has more than one reason to change.
- USE Inline Class when a class no longer earns its existence.
- USE Hide Delegate when clients know too much about an object's collaborator.
- USE Remove Middle Man when a forwarding object no longer hides useful detail.
- USE Introduce Foreign Method only when you cannot edit the class that should own the behavior.
- USE Introduce Local Extension when repeated foreign methods need a local, coherent extension point.
Organizing Data
- USE Self Encapsulate Field when direct field access blocks flexibility.
- USE Replace Data Value with Object when a primitive carries behavior, validation, or meaning.
- USE Change Value to Reference when identity and shared updates matter.
- USE Change Reference to Value when value semantics simplify ownership.
- USE Replace Array with Object when positions in a collection have names or rules.
- USE Duplicate Observed Data only when UI or framework synchronization forces it; keep synchronization explicit.
- USE Change Unidirectional Association to Bidirectional only when traversal is needed both ways.
- USE Change Bidirectional Association to Unidirectional when one direction is unnecessary coupling.
- USE Encapsulate Collection when external mutation can bypass invariants.
- USE Replace Record with Data Class when raw records need named access and behavior can grow safely.
- USE Replace Type Code with Class, Subclasses, or State/Strategy according to whether behavior varies by type.
- USE Replace Subclass with Fields when subclass variation is only data.
Simplifying Calls and Conditionals
- USE Decompose Conditional, Consolidate Conditional Expression, and Consolidate Duplicate Conditional Fragments to make branching intent visible.
- USE Remove Control Flag when loop or conditional state can be expressed directly.
- USE Replace Nested Conditional with Guard Clauses when it clarifies the normal path.
- USE Replace Conditional with Polymorphism only when repeated type-based behavior justifies it.
- USE Introduce Null Object when repeated null behavior has a stable meaning.
- USE Introduce Assertion when an assumption should be explicit during development.
- USE Rename Method, Add Parameter, Remove Parameter, Parameterize Method, or Replace Parameter with Explicit Methods to make caller intent clearer.
- USE Preserve Whole Object when callers pass several values from the same object.
- USE Replace Parameter with Method when the receiver can obtain the value itself without hidden coupling.
- USE Remove Setting Method when post-construction mutation should not be allowed.
- USE Hide Method when public surface exposes unnecessary operations.
- USE Replace Constructor with Factory Method when creation intent or subtype selection needs a name.
- USE Encapsulate Downcast when callers should not own cast details.
- USE Replace Error Code with Exception or Replace Exception with Test according to the expected failure model.
Generalization and Big Refactorings
- USE Pull Up Field, Pull Up Method, or Pull Up Constructor Body when duplicated superclass behavior is real.
- USE Push Down Method or Push Down Field when only some subclasses need the feature.
- USE Extract Subclass, Extract Superclass, or Extract Interface only when callers or variation points justify them.
- USE Collapse Hierarchy when inheritance no longer adds meaning.
- USE Form Template Method when similar algorithms differ in controlled steps.
- USE Replace Inheritance with Delegation when inheritance couples unrelated responsibilities.
- USE Replace Delegation with Inheritance only when the subtype relationship is genuine and stable.
- USE Tease Apart Inheritance when one hierarchy mixes multiple variation axes.
- USE Convert Procedural Design to Objects when data and behavior need clearer ownership.
- USE Separate Domain from Presentation when UI and policy are tangled.
- USE Extract Hierarchy when several types share behavior with meaningful variation.
Function-Level Rules
- One function should usually perform one coherent task.
- Keep abstraction level consistent inside a function.
- Remove hidden side effects unless the function's purpose is to cause them.
- Prefer guard clauses over deeply nested conditionals when that clarifies the happy path.
- Split phases like parsing, validation, computation, and I/O when they are mixed together.
- Keep variable scope tight.
- Delete dead code rather than comment it out.
Class and Module Rules
- A class or module should have a narrow reason to change.
- Separate policy from presentation, I/O, persistence, and framework details.
- Prefer composition of small focused units over god objects.
- Delete or inline abstractions that no longer pay for themselves.
- Do not create
utils, helpers, or common modules as a default response to duplication.
- Organize modules around concepts and behavior, not leftover convenience.
Rules for Working with Conditionals
- Replace repeated branching on type or status with stronger modeling when useful.
- Use lookup tables for stable mapping logic.
- Replace nested if/else pyramids with guard clauses, extracted predicates, or strategies when that reduces branching complexity.
- Keep explicit conditionals when they are simple and honest.
- Never introduce polymorphism merely to avoid a small local conditional.
Data and Mutation Rules
- Encapsulate mutation.
- Narrow write access to the smallest useful surface.
- Replace ad hoc mutations with intention-revealing operations.
- Remove duplicated update logic by centralizing state transitions.
- Prefer immutable intermediate values when that simplifies reasoning.
Error Handling Rules
- Refactor error handling to make the main path visible.
- Keep cleanup, validation, and recovery logic from drowning core behavior.
- Standardize similar error paths when they duplicate structure.
- Preserve existing error semantics unless intentionally changing behavior.
Review Rules
When reviewing or generating changes, actively look for:
- duplicated logic
- long functions
- long classes
- tangled control flow
- mixed abstraction levels
- feature envy
- shotgun surgery
- divergent change
- pass-through layers
- speculative generality
- hidden side effects
- global state reliance
- code that requires too much context to change safely
Forbidden Patterns
Do not generate or keep these patterns unless explicitly required and justified.
Big-Bang Rewrite
- replacing a working subsystem wholesale to “clean it up”
- rewriting before understanding current behavior
- changing structure and behavior in one giant move
Mixed-Intent Patches
- feature work mixed with huge unrelated renames
- behavior changes hidden inside cleanup
- code motion that makes review impossible
Abstracting Too Early
- introducing interfaces or strategy hierarchies before a second real need appears
- creating common libraries for one caller
- replacing understandable duplication with unclear shared code
Refactoring Theater
- renaming things while deeper design problems remain untouched
- introducing patterns instead of removing complexity
- creating more files, layers, or wrappers without improving changeability
Untested Structural Surgery
- large refactors without any safety net
- “cleanup” on fragile code with no verification strategy
- assuming behavior is obvious when it is not
Code Generation Rules
When asked to modify existing code, use this default order:
- understand current behavior
- identify the friction for the requested change
- add or improve the safety net if needed
- perform preparatory refactoring
- implement the behavioral change
- perform follow-up cleanup
- stop when the design is clearly better
Preferred first moves:
- rename badly named things
- extract coherent functions
- isolate side effects
- split mixed responsibilities
- move behavior closer to the owning concept
- remove duplication
- simplify conditionals
Preferred avoidance:
- unnecessary framework migrations
- gratuitous API redesign
- large hierarchy introduction
- replacing all old code with new code because the old code is ugly
Testing Rules
- Add characterization tests before risky edits when behavior is unclear.
- Keep tests focused on externally visible behavior.
- Update tests only when behavior intentionally changes.
- Do not couple tests to private implementation details more than necessary.
- Refactor tests too when they become noisy or duplicative.
- Keep test data expressive and minimal.
Stopping Rules
Stop refactoring when:
- the requested change is easy to implement
- the main smells blocking change are removed
- further cleanup would become speculative
- the next abstraction is not yet justified
- readability and local changeability are clearly improved
Review Checklist
Before finalizing any change, verify:
- Did we preserve observable behavior during refactoring?
- Did we separate structural change from behavior change where practical?
- Did we remove at least one real source of friction?
- Is the code easier to read than before?
- Is the code easier to test or change than before?
- Did we reduce duplication or accidental complexity?
- Did we avoid speculative abstraction?
- Did we avoid a giant mixed patch?
- Did names improve?
- Did control flow become simpler?
- Did responsibilities become clearer?
If any answer is no, revise before shipping.
Final Instruction
When uncertain, choose the next small, behavior-preserving transformation
that makes the requested change easier and the code easier to understand.
Reject approaches that gamble on large rewrites or mix too many intentions at once.
1---
2name: book-refactoring-full
3description: >-
4 Refactoring (Martin Fowler) — Full rules — comprehensive mandatory coding standards. Use when asked to apply Refactoring principles or review code against Refactoring standards.
5origin: "github.com/ciembor/agent-rules-books (MIT)"
6license: MIT
7version: "1.0.0"
8compatibility: "yana-ai >= 0.14.0"
9metadata:
10 source: https://skillmd.com/skills/yanacuti1121/book-refactoring-full
11---
12
13# OBEY Refactoring by Martin Fowler
14
15## Purpose
16
17This repository follows the discipline of **Refactoring** in the sense of Martin Fowler:
18improve the internal structure of code **without changing its observable behavior**.
19
20All code generation, edits, and reviews must optimize for:
21- small behavior-preserving changes
22- clearer names and simpler control flow
23- lower duplication
24- smaller units of responsibility
25- explicit movement from bad design toward good design
26- steady design improvement as part of daily work
27
28This file is a binding engineering policy: `MUST` is binding, `SHOULD` is a strong default, and `MUST NOT` is forbidden.
29
30---
31
32## Primary Directive
33
34When modifying existing code, do **not** start by rewriting large areas.
35Start by making the next safe structural improvement that makes the desired change easier.
36
37Prefer:
381. establish a safety net
392. make a preparatory refactoring
403. make the functional change
414. refactor again if needed
42
43Reject changes that bundle large functional changes with unrelated structural churn.
44
45---
46
47## What Counts as Refactoring
48
49Refactoring here means:
50- changing structure without changing external behavior
51- applying small, composable transformations
52- removing code smells before or during feature work
53- making the next change easier
54- improving readability, locality, and testability
55
56Refactoring here does **not** mean:
57- large rewrites
58- unverified cleanup
59- “modernization” with unclear behavioral impact
60- renaming everything at once
61- mixing architecture migration, feature work, and cleanup in one uncontrolled patch
62
63---
64
65## Non-Negotiable Rules
66
671. **Preserve Behavior**
68 - Refactorings must preserve observable behavior.
69 - If behavior must change, isolate the behavior change from structural refactoring.
70 - Never disguise a feature change as a refactoring.
71
722. **Work in Small Steps**
73 - Prefer many small safe edits over one large transformation.
74 - Each step should be understandable and reversible.
75 - If a patch feels too large to reason about locally, split it.
76
773. **Keep the System Running**
78 - Do not leave code in a broken intermediate state unless explicitly asked for a draft.
79 - Every refactoring sequence should maintain a runnable, buildable state where practical.
80
814. **Refactor Before and After Feature Work**
82 - If code is hard to change, first reshape it.
83 - After the feature lands, clean remaining structural debt introduced by the change.
84
855. **Use the Simplest Helpful Refactoring**
86 - Do not introduce patterns or abstractions earlier than needed.
87 - Prefer local simplification before large-scale abstraction.
88
89---
90
91## Safety Rules
92
93### Tests and Verification
941. Create or identify a safety net before risky refactoring.
952. Prefer characterization tests when working on unclear existing behavior.
963. If tests are absent, make the smallest changes possible and improve testability first.
974. Keep refactoring and test updates aligned with preserved behavior.
985. Never delete a failing test just to complete a refactoring.
99
100### Commit and Patch Discipline
1011. Separate structural edits from behavior changes whenever practical.
1022. Group related refactorings together.
1033. Avoid giant mixed commits that rename, move, redesign, and change logic all at once.
1044. Prefer reviewable sequences of transformations.
105
106### Preparatory Refactoring
107Before implementing a feature, ask:
108- what makes this change awkward?
109- what local structural change would make it straightforward?
110- can I rename, extract, move, split, or inline first?
111
112Do the preparatory refactoring before the feature change.
113
114---
115
116## Code Smell Policy
117
118When modifying code, actively look for these smells.
119
120### Duplicated Code
121- Duplicate logic is a default target for elimination.
122- Remove duplication by extracting shared behavior, not by introducing vague utility dumping grounds.
123- Do not abstract coincidental similarity.
124
125### Long Functions
126- Split long functions when they mix responsibilities, levels of abstraction, or phases of work.
127- Extract meaningful chunks with names that explain intent.
128- Do not create micro-method noise with no explanatory value.
129
130### Long Parameter Lists
131- Replace repeated clumps with parameter objects or richer domain objects where appropriate.
132- Remove boolean flags that switch behavior.
133- Avoid signatures that require callers to memorize argument order.
134
135### Global Data and Hidden Dependencies
136- Reduce reliance on globals, singletons, and ambient context.
137- Make dependencies explicit where possible.
138- Refactor toward injection, parameters, or clear ownership.
139
140### Divergent Change
141- If one class changes for many different reasons, split responsibilities.
142- Separate business logic, formatting, transport, persistence, and integration concerns.
143
144### Shotgun Surgery
145- If one change forces edits across many files, centralize the knowledge.
146- Introduce a better boundary or clearer ownership.
147
148### Feature Envy
149- If a method mostly manipulates another object's data, move it or reshape the model.
150- Put behavior near the data or concept it belongs to.
151
152### Data Clumps and Primitive Obsession
153- Replace repeated primitive bundles with meaningful types.
154- Give recurring business concepts names and validation.
155
156### Switch Statements and Conditionals
157- Reduce repeated branching on type or mode when polymorphism, tables, strategies, or better data structures fit.
158- Do not replace a single honest conditional with needless indirection.
159
160### Temporary Fields and Weird Lifecycles
161- Remove fields that exist only for unusual code paths when a separate object or clearer phase model is better.
162- Prefer modeling states explicitly over half-initialized objects.
163
164### Middle Man and Speculative Generality
165- Remove forwarding layers that add no value.
166- Delete abstractions created “just in case” if they are not earning their keep.
167
168---
169
170## Preferred Refactoring Moves
171
172### Naming Refactorings
173- Rename variables to reveal intent.
174- Rename functions to describe behavior, not mechanism.
175- Rename types and modules to align with problem-domain terminology.
176- Rename before deeper refactoring when bad names block understanding.
177
178### Extraction Refactorings
179- Extract function when a block has a coherent purpose.
180- Extract variable when an expression is hard to read.
181- Extract class when one class has multiple reasons to change.
182- Extract module when a file mixes unrelated concerns.
183
184### Movement Refactorings
185- Move function to the module or type where the data or concept lives.
186- Move field when ownership is clearer elsewhere.
187- Move statements to group related operations and reduce cognitive jumps.
188
189### Simplification Refactorings
190- Inline accidental abstractions.
191- Collapse unnecessary layers.
192- Replace nested conditionals with guard clauses where it improves clarity.
193- Consolidate duplicate conditional fragments.
194
195### Data Refactorings
196- Encapsulate mutable state.
197- Replace magic values with named constants or domain types.
198- Introduce parameter objects for repeated argument groups.
199- Replace raw collections with named abstractions when behavior accumulates around them.
200
201---
202
203## Refactoring Catalog Index
204
205### Composing Methods
206- USE Extract Method when a code fragment has a coherent purpose and a useful name.
207- USE Inline Method when a method body is clearer than its indirection.
208- USE Inline Temp when a temporary variable obscures a direct expression.
209- USE Replace Temp with Query when a calculated value deserves a named query and can be reused safely.
210- USE Introduce Explaining Variable when a complex expression needs named parts.
211- USE Split Temporary Variable when one variable carries multiple meanings.
212- USE Remove Assignments to Parameters when parameter mutation obscures input meaning.
213- USE Replace Method with Method Object when local state prevents clean extraction.
214- USE Substitute Algorithm when a clearer algorithm can replace a tangled one without changing behavior.
215
216### Moving Features
217- USE Move Method or Move Field when behavior or state belongs more naturally to another object.
218- USE Extract Class when one class has more than one reason to change.
219- USE Inline Class when a class no longer earns its existence.
220- USE Hide Delegate when clients know too much about an object's collaborator.
221- USE Remove Middle Man when a forwarding object no longer hides useful detail.
222- USE Introduce Foreign Method only when you cannot edit the class that should own the behavior.
223- USE Introduce Local Extension when repeated foreign methods need a local, coherent extension point.
224
225### Organizing Data
226- USE Self Encapsulate Field when direct field access blocks flexibility.
227- USE Replace Data Value with Object when a primitive carries behavior, validation, or meaning.
228- USE Change Value to Reference when identity and shared updates matter.
229- USE Change Reference to Value when value semantics simplify ownership.
230- USE Replace Array with Object when positions in a collection have names or rules.
231- USE Duplicate Observed Data only when UI or framework synchronization forces it; keep synchronization explicit.
232- USE Change Unidirectional Association to Bidirectional only when traversal is needed both ways.
233- USE Change Bidirectional Association to Unidirectional when one direction is unnecessary coupling.
234- USE Encapsulate Collection when external mutation can bypass invariants.
235- USE Replace Record with Data Class when raw records need named access and behavior can grow safely.
236- USE Replace Type Code with Class, Subclasses, or State/Strategy according to whether behavior varies by type.
237- USE Replace Subclass with Fields when subclass variation is only data.
238
239### Simplifying Calls and Conditionals
240- USE Decompose Conditional, Consolidate Conditional Expression, and Consolidate Duplicate Conditional Fragments to make branching intent visible.
241- USE Remove Control Flag when loop or conditional state can be expressed directly.
242- USE Replace Nested Conditional with Guard Clauses when it clarifies the normal path.
243- USE Replace Conditional with Polymorphism only when repeated type-based behavior justifies it.
244- USE Introduce Null Object when repeated null behavior has a stable meaning.
245- USE Introduce Assertion when an assumption should be explicit during development.
246- USE Rename Method, Add Parameter, Remove Parameter, Parameterize Method, or Replace Parameter with Explicit Methods to make caller intent clearer.
247- USE Preserve Whole Object when callers pass several values from the same object.
248- USE Replace Parameter with Method when the receiver can obtain the value itself without hidden coupling.
249- USE Remove Setting Method when post-construction mutation should not be allowed.
250- USE Hide Method when public surface exposes unnecessary operations.
251- USE Replace Constructor with Factory Method when creation intent or subtype selection needs a name.
252- USE Encapsulate Downcast when callers should not own cast details.
253- USE Replace Error Code with Exception or Replace Exception with Test according to the expected failure model.
254
255### Generalization and Big Refactorings
256- USE Pull Up Field, Pull Up Method, or Pull Up Constructor Body when duplicated superclass behavior is real.
257- USE Push Down Method or Push Down Field when only some subclasses need the feature.
258- USE Extract Subclass, Extract Superclass, or Extract Interface only when callers or variation points justify them.
259- USE Collapse Hierarchy when inheritance no longer adds meaning.
260- USE Form Template Method when similar algorithms differ in controlled steps.
261- USE Replace Inheritance with Delegation when inheritance couples unrelated responsibilities.
262- USE Replace Delegation with Inheritance only when the subtype relationship is genuine and stable.
263- USE Tease Apart Inheritance when one hierarchy mixes multiple variation axes.
264- USE Convert Procedural Design to Objects when data and behavior need clearer ownership.
265- USE Separate Domain from Presentation when UI and policy are tangled.
266- USE Extract Hierarchy when several types share behavior with meaningful variation.
267
268---
269
270## Function-Level Rules
271
2721. One function should usually perform one coherent task.
2732. Keep abstraction level consistent inside a function.
2743. Remove hidden side effects unless the function's purpose is to cause them.
2754. Prefer guard clauses over deeply nested conditionals when that clarifies the happy path.
2765. Split phases like parsing, validation, computation, and I/O when they are mixed together.
2776. Keep variable scope tight.
2787. Delete dead code rather than comment it out.
279
280---
281
282## Class and Module Rules
283
2841. A class or module should have a narrow reason to change.
2852. Separate policy from presentation, I/O, persistence, and framework details.
2863. Prefer composition of small focused units over god objects.
2874. Delete or inline abstractions that no longer pay for themselves.
2885. Do not create `utils`, `helpers`, or `common` modules as a default response to duplication.
2896. Organize modules around concepts and behavior, not leftover convenience.
290
291---
292
293## Rules for Working with Conditionals
294
2951. Replace repeated branching on type or status with stronger modeling when useful.
2962. Use lookup tables for stable mapping logic.
2973. Replace nested if/else pyramids with guard clauses, extracted predicates, or strategies when that reduces branching complexity.
2984. Keep explicit conditionals when they are simple and honest.
2995. Never introduce polymorphism merely to avoid a small local conditional.
300
301---
302
303## Data and Mutation Rules
304
3051. Encapsulate mutation.
3062. Narrow write access to the smallest useful surface.
3073. Replace ad hoc mutations with intention-revealing operations.
3084. Remove duplicated update logic by centralizing state transitions.
3095. Prefer immutable intermediate values when that simplifies reasoning.
310
311---
312
313## Error Handling Rules
314
3151. Refactor error handling to make the main path visible.
3162. Keep cleanup, validation, and recovery logic from drowning core behavior.
3173. Standardize similar error paths when they duplicate structure.
3184. Preserve existing error semantics unless intentionally changing behavior.
319
320---
321
322## Review Rules
323
324When reviewing or generating changes, actively look for:
325- duplicated logic
326- long functions
327- long classes
328- tangled control flow
329- mixed abstraction levels
330- feature envy
331- shotgun surgery
332- divergent change
333- pass-through layers
334- speculative generality
335- hidden side effects
336- global state reliance
337- code that requires too much context to change safely
338
339---
340
341## Forbidden Patterns
342
343Do not generate or keep these patterns unless explicitly required and justified.
344
345### Big-Bang Rewrite
346- replacing a working subsystem wholesale to “clean it up”
347- rewriting before understanding current behavior
348- changing structure and behavior in one giant move
349
350### Mixed-Intent Patches
351- feature work mixed with huge unrelated renames
352- behavior changes hidden inside cleanup
353- code motion that makes review impossible
354
355### Abstracting Too Early
356- introducing interfaces or strategy hierarchies before a second real need appears
357- creating common libraries for one caller
358- replacing understandable duplication with unclear shared code
359
360### Refactoring Theater
361- renaming things while deeper design problems remain untouched
362- introducing patterns instead of removing complexity
363- creating more files, layers, or wrappers without improving changeability
364
365### Untested Structural Surgery
366- large refactors without any safety net
367- “cleanup” on fragile code with no verification strategy
368- assuming behavior is obvious when it is not
369
370---
371
372## Code Generation Rules
373
374When asked to modify existing code, use this default order:
3751. understand current behavior
3762. identify the friction for the requested change
3773. add or improve the safety net if needed
3784. perform preparatory refactoring
3795. implement the behavioral change
3806. perform follow-up cleanup
3817. stop when the design is clearly better
382
383Preferred first moves:
384- rename badly named things
385- extract coherent functions
386- isolate side effects
387- split mixed responsibilities
388- move behavior closer to the owning concept
389- remove duplication
390- simplify conditionals
391
392Preferred avoidance:
393- unnecessary framework migrations
394- gratuitous API redesign
395- large hierarchy introduction
396- replacing all old code with new code because the old code is ugly
397
398---
399
400## Testing Rules
401
4021. Add characterization tests before risky edits when behavior is unclear.
4032. Keep tests focused on externally visible behavior.
4043. Update tests only when behavior intentionally changes.
4054. Do not couple tests to private implementation details more than necessary.
4065. Refactor tests too when they become noisy or duplicative.
4076. Keep test data expressive and minimal.
408
409---
410
411## Stopping Rules
412
413Stop refactoring when:
414- the requested change is easy to implement
415- the main smells blocking change are removed
416- further cleanup would become speculative
417- the next abstraction is not yet justified
418- readability and local changeability are clearly improved
419
420---
421
422## Review Checklist
423
424Before finalizing any change, verify:
425- Did we preserve observable behavior during refactoring?
426- Did we separate structural change from behavior change where practical?
427- Did we remove at least one real source of friction?
428- Is the code easier to read than before?
429- Is the code easier to test or change than before?
430- Did we reduce duplication or accidental complexity?
431- Did we avoid speculative abstraction?
432- Did we avoid a giant mixed patch?
433- Did names improve?
434- Did control flow become simpler?
435- Did responsibilities become clearer?
436
437If any answer is no, revise before shipping.
438
439---
440
441## Final Instruction
442
443When uncertain, choose the next **small, behavior-preserving transformation**
444that makes the requested change easier and the code easier to understand.
445Reject approaches that gamble on large rewrites or mix too many intentions at once.