Refactoring.Guru — smells e técnicas catalogadas
Definition
Este conceito destila o livro refactoring-guru em regras executáveis para agentes de IA, conforme publicado no repositório agent-rules-books (v0.5, MIT, fork de ciembor/agent-rules-books). Cada livro tem 3 formatos (full canônico, mini recomendado, nano compacto); esta página documenta o mini — o formato usado no dia a dia para instruir Codex, Cursor e Claude Code sem estourar a janela de contexto.
Ponto de partida: Refactoring.Guru — smells e técnicas catalogadas. Ver detalhes completos do
minina seção “Regras originais (mini)” abaixo, extraída verbatim deraw/vibecoding/articles/agent-rules-books.md.
Quando usar
Extraído do header ## When to use do mini (tradução e adaptação para founder/PM não-técnico abaixo; original em inglês mantido na seção final):
- Use quando a dimensão que este livro governa for o risco principal da tarefa do agente (legibilidade, arquitetura, legado, dados, etc.).
- Prefira este livro como contrato verificável em vez de pedir genérico tipo “faça bem feito” — ver hub regras-de-agentes-a-partir-de-livros para escolher entre os 14.
Viés principal a corrigir e regras de decisão
O mini organiza as regras em ## Primary bias to correct e ## Decision rules. Para o founder, isso vira checklist de revisão do plano e do PR:
- Leia o
Primary biascomo o erro que o agente comete quando só recebe instrução vaga (ex.: “código que roda não é código limpo” em Clean Code; “complexidade acidental” em Philosophy of SD). - Transforme cada
Decision ruleem critério de pronto da issue (especificacao-de-issues-para-agentes) e em item doFinal checklistque você cobra no review.
Consulte a transcrição completa na seção final e marque na issue quais regras desta página se aplicam (ex.: scoped rules só em src/domain/** para DDD, só em src/infra/** para Release It!).
Gatilhos (Trigger rules)
Os Trigger rules do mini indicam quando o agente deve quebrar a tarefa em passos menores ou trocar de padrão (ex.: “quando função mistura setup/validação/computação/efeito, separe fases” — Clean Code; “quando boundary vaza framework para dentro, fortaleça adapter” — Clean Code/Clean Architecture). Para o founder, são sinais para pedir ao agente: “pare, proponha plano antes de codar” (plan-first-com-agentes-de-ia).
Checklist final para o founder cobrar do agente
O mini fecha com ## Final checklist — perguntas que você faz no PR sem precisar ler o livro:
- O leitor consegue seguir a mudança localmente, sem pular arquivos?
- Nomes/APIs carregam significado sem comentário narrativo?
- Mutação é explícita e o caminho feliz permanece legível?
- Detalhes de framework/persistência/vendor ficaram atrás de boundaries?
- Pelo menos um smell foi removido na área tocada, sem alargar o escopo silenciosamente?
- Testes protegem o contrato mudado e foram efetivamente rodados?
Adapte o checklist ao livro: para DDIA troque por “timeout/retry/circuit breaker definidos?”; para DDD troque por “linguagem ubíqua respeitada? aggregate protege invariantes?”.
Implications
Para o founder/PM não-técnico, esta página transforma conhecimento de livro — normalmente inacessível sem 300+ páginas de leitura — em instrução operacional colável no AGENTS.md/skills. Em vez de torcer para o agente “saber” o livro, você cola 30 regras testáveis e mede no vibe-coded-crap (74/100 com mini vs 46/100 só citando o título). Isso conecta agents-md-como-instrucao-operacional (zona 60-150 linhas, pointers), plan-first-com-agentes-de-ia (plano melhora com regras concretas) e ciclo-issue-branch-pr-merge (PR só mergea se passa no checklist).
Related Concepts
- refactoring-e-legado-como-operar-codigo-existente
- regras-de-agentes-a-partir-de-livros
- refactoring
- ciclo-issue-branch-pr-merge
- agent-rules-books — repositório fonte desta coleção
- vibe-coding — prática onde estas regras são aplicadas
Regras originais (mini) — transcrição verbatim
Fonte:
raw/vibecoding/articles/agent-rules-books.mdseção## refactoring-guru— conteúdominiextraído viahttps://raw.githubusercontent.com/mattpocock/agent-rules-books/main/refactoring-guru/refactoring-guru.mini.mdem 2026-08-29. Transcrição fiel; não substitui a leitura do livro.
OBEY Refactoring.Guru
## When to use
Use when changing existing code where code smells, refactoring technique choice, behavior preservation, and cleanup scope control matter.
## Primary bias to correct
Refactoring is not general cleanup or pattern application. It is a small, smell-driven, behavior-preserving treatment with verification and a stop condition.
## Decision rules
- Separate refactoring from feature work and bug fixes. If behavior changes, name it as behavior change and isolate it from structural edits.
- Diagnose the smell before choosing a technique: symptom, maintenance cost, scope, expected cleaner end state, verification path, and stop condition.
- Prefer the smallest treatment that directly reduces the diagnosed smell; escalate only when the smaller technique is blocked.
- Keep the code runnable and understandable through small named transformations rather than broad redesign.
- Run relevant checks after risky moves, public interface changes, state-flow changes, or algorithm substitution.
- Stop when the named smell is gone or materially reduced; record new smells separately unless they block the current change.
- Use the Rule of Three: tolerate uncertain duplication early, but refactor the third similar occurrence unless the similarity is coincidental.
- Treat technical debt as compounding cost; pay down the debt that slows current change speed, correctness, or team understanding.
- Scan smells by category: bloaters, object-orientation abusers, change preventers, dispensables, couplers, and incomplete library gaps.
- For bloaters, prefer extraction, parameter/data modeling, and responsibility splits before creating method objects, subclasses, or interfaces.
- For switch/type-code smells, isolate the decision first; use polymorphism, subclasses, or state/strategy only when variation is stable and repeated.
- For change preventers, move behavior and data toward the owner of the changing concept so one conceptual change has one main edit site.
- For dispensables, delete or inline unused structure, but check public, generated, reflected, serialized, plugin-facing, and framework extension uses first.
- For couplers, reduce navigation and private knowledge; keep delegating layers only when they hide volatile structure, policy, or a real boundary.
- Use comments for rationale, constraints, contracts, or hard algorithms; use names, variables, methods, or assertions when comments explain unclear code.
- Keep behavior with the data it changes unless separation deliberately supports interchangeable behavior.
- Encapsulation is not finished by adding getters and setters; move behavior inward when callers are still manipulating exposed data.
- Avoid speculative abstractions: do not create wrappers, parameter objects, interfaces, superclasses, or hierarchy variants without a real concept or client.
- Preserve public compatibility or provide a transition path when changing signatures, constructors, visibility, type hierarchy, or externally reachable APIs.
- Before extraction or movement, identify inputs, outputs, mutated variables, callers, visibility, construction paths, and invariants.
- Before condition consolidation or algorithm substitution, verify side effects, ordering, truth tables, edge cases, and performance-sensitive behavior.
- Before data reorganization, decide identity, value/reference semantics, mutability, equality, lifecycle ownership, association direction, and synchronization.
- Before generalization changes, prove shared behavior is real; preserve substitutability and avoid inheriting unused behavior.
- Choose exceptions deliberately: a simple conditional, useful comment, intentional strategy separation, small extension point, or clear duplication may be better than a mechanical treatment.
## Trigger rules
- When a method needs comments, scrolling, or local-state reconstruction, try `Extract Method`; use `Replace Temp with Query`, `Introduce Parameter Object`, or `Preserve Whole Object` when locals block extraction.
- When a class has multiple reasons to change, use `Extract Class`; use subclass/interface extraction only for stable variants or real client-facing subsets.
- When primitives, arrays, magic numbers, or type codes carry meaning, model the concept only if the model adds naming, validation, behavior, or safer variation handling.
- When a parameter list grows beyond local reasoning, replace derived parameters, preserve a whole object, or introduce a parameter object only for a real recurring concept.
- When the same change requires edits across many files, move methods/fields or extract ownership so the knowledge is centralized.
- When client code navigates object chains, hide the delegate or move behavior closer to the data; do not add pure forwarding.
- When a class mostly forwards, remove the middle man unless it protects boundary policy or volatile structure.
- When a method both queries and mutates, separate query from modifier unless atomic read-modify behavior is the public contract.
- When branches repeat behavior, decompose, consolidate, or move duplicate fragments only after checking side effects and execution order.
- When null checks dominate, introduce a null object only if absence can obey the same interface; keep absence explicit when it is an error.
- When inheritance creates refused bequest or intimacy, push members down or replace inheritance with delegation.
- When deleting dead or speculative code, verify external reachability and test-only access before removal.
- When a library class is incomplete, use a foreign method for one narrow gap and a local extension only for substantial repeated gaps.
- When cleanup keeps expanding, stop at the diagnosed smell and report the next smell separately.
## Final checklist
- Is this change clearly refactoring, feature work, or bug fixing?
- Which smell was diagnosed, and what cost did it create?
- Was the smallest suitable treatment used before riskier structure?
- Did behavior stay preserved under relevant checks?
- Did the named smell become materially better?
- Did the change avoid speculative abstraction and mechanical pattern use?
- Were public compatibility, state flow, and ownership checked?
- Is any intentionally untreated smell documented rather than hidden?