agentleFS
BappozBappoz/My-Claude-Skills/skills/engineering/refactoring/SKILL.md

refactoring

Skill1 starsChanged 4 months agoMITView on GitHub

Refatoração segura: catálogo de code smells, técnicas de Fowler (extract/inline/move/rename), refatorar sob rede de testes, strangler fig e regra do escoteiro. Use quando o usuário mencionar: "refatorar", "refactoring", "code smell", "limpar o código", "melhorar sem mudar comportamento", "extract method", "código legado", "reduzir complexidade", "dívida técnica". Liga com [[testing]] e [[tech-debt]].

58 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use dependency-management, multi-agent-orchestration and 5 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • dkprogSkill

    dependency-management

    Apply when wiring dependencies, integrating external services, or designing interfaces between modules. Ensures loose coupling through dependency injection, interface segregation, and proper abstraction boundaries.

    Also in 3 projects that use this

  • javalenciacaiSkill

    multi-agent-orchestration

    Design and coordinate multi-agent systems where specialized agents work together to solve complex problems. Covers agent communication, task delegation, workflow orchestration, and result aggregation. Use when building coordinated agent teams, complex workflows, or systems requiring specialized expertise across domains.

    Also in 3 projects that use this

  • MicrosoftSkill

    error-handling

    统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。

    Also in 7 projects that use this

  • AWSSkill

    planning

    Discovers user intent and generates a structured, step-by-step plan for model customization workflows. This skill must always be activated alongside any other skill when the user's request relates to model customization — including fine-tuning, training, building, customizing, reviewing data, or getting advice on approach, regardless of domain. Do not skip this skill even if the immediate ask is narrow (e.g., reviewing data format or a single workflow step), because planning discovers the full scope of work needed. Also activate when the user wants to resume, continue, or modify an existing plan.

    Also in 6 projects that use this

  • AnthropicSkill

    documentation

    Write and maintain technical documentation. Trigger with "write docs for", "document this", "create a README", "write a runbook", "onboarding guide", or when the user needs help with any form of technical writing — API docs, architecture docs, or operational runbooks.

    Also in 9 projects that use this

  • diego-tobalinaSkill

    logging

    Logging best practices for Java (SLF4J/Logback) and Node.js (Winston/Pino). Use for structured logging, log levels, and avoiding sensitive data exposure.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 53 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    No mesmo commit/PR de uma feature (mistura difícil de revisar e reverter).

    line 60
  2. Distinctive:

    Commit atômico "refactor: ..." separado de features.

    line 68

“Common” is measured: kept by at least 6 in 10 of the 53 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Refactoring

Você atua como engenheiro que melhora código com disciplina. Definição estrita: refatorar é mudar a estrutura interna sem mudar o comportamento observável. Se o comportamento muda, não é refatoração — é feature ou bugfix (faça separado). A rede de segurança é sempre o teste.

A lei nº1: refatore sob testes

Sem testes que provem que o comportamento não mudou, você não está refatorando — está reescrevendo e torcendo. Antes de mexer em código legado sem cobertura, escreva testes de caracterização (que capturam o comportamento atual, mesmo que "errado") — ver [[testing]].

1. Testes verdes  →  2. Um passo pequeno de refatoração  →  3. Rodar testes  →  repetir

Passos pequenos e reversíveis. Commit a cada passo verde. Nunca refatore e adicione feature no mesmo commit.

Catálogo de code smells (o que caçar)

SmellSinalTécnica
Long methodFunção que não cabe na cabeçaExtract Method
Large classClasse que faz de tudoExtract Class, mover responsabilidade
Duplicated codeCopiar-colarExtract Method/Function, subir p/ base
Long parameter list5+ paramsIntroduce Parameter Object
Feature envyMétodo usa mais dados de outra classeMove Method
Primitive obsessionString/int para tudoValue Object / tipo próprio
Shotgun surgeryUma mudança toca 10 arquivosJuntar o que muda junto (coesão)
Divergent changeUma classe muda por N razõesSeparar responsabilidades
Comentário explicando código ruimComentário compensa nome ruimRename + Extract (código autoexplicativo)

Técnicas fundamentais (Fowler)

  • Extract Function/Method — nomeie um trecho pelo que faz. A técnica mais usada.
  • Inline — o inverso, quando a indireção não paga.
  • Rename — o nome certo elimina comentários e confusão. Barato, altíssimo retorno.
  • Move — leve o método/campo para onde os dados que ele usa vivem.
  • Extract Variable — nomeie subexpressões complexas.
  • Replace Conditional with Polymorphism — troque switch por tipos quando o ramo é sobre "tipo de coisa".
  • Introduce Parameter Object — agrupe params que andam juntos.

Refatorar legado em escala: Strangler Fig

Não reescreva um sistema grande de uma vez (big-bang quase sempre falha). Estrangule: construa o novo ao redor do velho, redirecione uma fatia de cada vez, e remova o velho quando nada mais o usa. Sempre entregável, sempre reversível.

Regra do escoteiro (Boy Scout Rule)

"Deixe o código mais limpo do que encontrou." Refatoração contínua e pequena, no código que você já está tocando, evita a dívida virar reescrita. Melhor que o "grande projeto de refatoração" (que raramente é priorizado — ver [[tech-debt]]).

Quando NÃO refatorar

  • Código que você não vai tocar e funciona (refatorar tem risco/custo; sem retorno, deixe).
  • Sem testes e sem tempo de escrevê-los (você vai quebrar algo).
  • No mesmo commit/PR de uma feature (mistura difícil de revisar e reverter).
  • Perto de um deadline crítico, em código de alto risco, sem necessidade.

Fluxo

  1. Identifique o smell e por que dói agora (serve ao trabalho atual?).
  2. Garanta cobertura de testes (caracterização se preciso).
  3. Aplique a técnica em passos pequenos, rodando testes a cada passo.
  4. Commit atômico "refactor: ..." separado de features.
  5. Pare quando o código está bom o suficiente — não persiga perfeição.

Recursos externos

RecursoO que pegar
Refactoring (Martin Fowler)Catálogo canônico de smells e técnicas.
refactoring.guruSmells + técnicas com exemplos visuais.
Strangler Fig (Fowler)Migrar legado incrementalmente.
Working Effectively with Legacy Code (ref.)Testes de caracterização, quebrar dependências.
[[testing]] · [[tech-debt]]Rede de segurança e priorização da dívida.

Do / Don't

DoDon't
Refatorar sob testes verdesReescrever sem rede
Passos pequenos, commit a cada verdeRefatoração gigante de uma vez
Separar refactor de featureMisturar tudo num PR
Rename/Extract para clarezaComentar código ruim em vez de melhorá-lo
Strangler fig no legadoBig-bang rewrite

Checklist

  • Comportamento observável NÃO muda (senão é feature/bugfix)
  • Cobertura de testes garante a rede (caracterização se legado)
  • Smell identificado + técnica apropriada
  • Passos pequenos, testes rodando a cada passo
  • Commit "refactor:" separado de features
  • Legado grande via strangler fig, não big-bang
  • Parou no "bom o suficiente" (sem gold-plating)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.