Refactoring improves the structure without changing behavior.
Refactoring melhora a estrutura sem mudar o comportamento.Aula
Refactoring proposals
Nível: C1
Objetivo
Propor refactorings em C1 com motivation, scope, safety net, migration steps, expected payoff e rollout. O foco é refactor que sobrevive à review, não 'isso precisa de refactor' sem plano.
Explicação
Refactoring proposal em C1 não é 'isso precisa de refactor'; é um plano que sobrevive à review. Seis blocos:
1. Motivation
Por que refatorar, com dado. C1 cita: 'this module has 7 unrelated responsibilities; SRP suggests splitting it' ou 'this code has a 40% test coverage gap, and we are scared to change it'. Motivation C1 é o que justifica o trabalho, não 'o código está feio'.
2. Scope
O que está dentro e fora do refactor. C1 cita: 'in scope: extract the validation into a helper, split the class in two; out of scope: rename the methods, change the persistence layer'. Scope C1 delimita a conversa e impede feature creep.
3. Safety net
Como garantir que o refactor não quebra. C1 cita: 'we have 90% test coverage on this module, and we will add characterization tests for the parts that lack coverage' ou 'we will run the canary in production for 24h after the refactor'. Safety net é o que convence o time de que o refactor é seguro.
4. Migration steps
A ordem das mudanças. C1 cita: 'step 1, extract the helper; step 2, update the callers; step 3, split the class; step 4, remove the old code'. Migration steps C1 são pequenas e verificáveis, não 'reescrever tudo'.
5. Expected payoff
O que o time ganha. C1 cita: 'after the refactor, the time to add a new validation rule drops from 1 day to 1 hour' ou 'the test coverage goes from 40% to 80%'. Payoff C1 é mensurável e alinhado ao time, não 'fica mais limpo'.
6. Rollout
Como o refactor chega em produção. C1 cita: 'PR 1: extract helper; PR 2: update callers; PR 3: split class; each PR is independently deployable' ou 'behind a feature flag for the first 24h'. Rollout C1 transforma o refactor em entrega verificável.
Exemplos
| Inglês | Tradução | Observação |
|---|---|---|
| This module has 7 unrelated responsibilities; SRP suggests splitting it. | Este módulo tem 7 responsabilidades não relacionadas; SRP sugere separá-lo. | Motivation: SRP + número. |
| In scope: extract the validation into a helper, split the class in two. Out of scope: rename methods, change the persistence layer. | Dentro do escopo: extrair a validação em um helper, separar a classe em duas. Fora do escopo: renomear métodos, mudar a camada de persistência. | Scope: delimita o refactor. |
| We have 90% test coverage on this module, and we will add characterization tests for the parts that lack coverage. | Temos 90% de cobertura neste módulo, e vamos adicionar testes de caracterização para as partes sem cobertura. | Safety net: cobertura + characterization tests. |
| Step 1: extract the helper. Step 2: update the callers. Step 3: split the class. Step 4: remove the old code. | Passo 1: extrair o helper. Passo 2: atualizar os callers. Passo 3: separar a classe. Passo 4: remover o código antigo. | Migration steps: pequenos e verificáveis. |
| After the refactor, the time to add a new validation rule drops from 1 day to 1 hour. | Depois do refactor, o tempo para adicionar uma nova regra de validação cai de 1 dia para 1 hora. | Payoff: mensurável e alinhado ao time. |
Erros comuns
- Refactor sem motivation: 'isso está feio' não convence; 'SRP sugere separar' convence.
- Escopo sem delimitação: 'vamos refatorar tudo' é big-bang; C1 delimita com in scope e out of scope.
- Sem safety net: refactor sem cobertura ou canary em produção é aposta, não engenharia.
- Migration em um passo: 'vamos reescrever' não é plano; passos pequenos e verificáveis são.
- Payoff vago: 'fica mais limpo' não convence liderança; 'tempo cai de 1 dia para 1 hora' convence.
Prática guiada
Reescreva cada bloco abaixo no padrão C1 de refactoring proposal.
- Motivation: cite o princípio e o número (SRP + 7 responsabilidades).
- Scope: delimite com 'in scope' e 'out of scope'.
- Safety net: cite cobertura, characterization tests, ou canary.
- Migration steps: pequenos e verificáveis, com PRs independentes.
- Payoff: mensurável e alinhado ao time.
- Rollout: cada PR deployable; feature flag se necessário.
Resumo
Refactoring proposal C1 tem seis blocos: motivation (princípio + número), scope (in/out of scope), safety net (cobertura + characterization tests + canary), migration steps (pequenos e verificáveis), expected payoff (mensurável), rollout (PRs independentes). Sem motivation, é opinião; sem safety net, é aposta; sem payoff, é 'fica mais limpo'.
Vocabulário
Palavras principais
The motivation is SRP; the module has 7 unrelated responsibilities.
A motivação é SRP; o módulo tem 7 responsabilidades não relacionadas.The safety net is 90% test coverage and a 24h canary in production.
A rede de segurança é 90% de cobertura e canário de 24h em produção.Characterization tests document what the code actually does, not what it should do.
Testes de caracterização documentam o que o código realmente faz, não o que deveria fazer.Each migration step is independently deployable.
Cada passo de migração é independentemente deployable.The expected payoff is reducing the time to add a new rule from 1 day to 1 hour.
O ganho esperado é reduzir o tempo de adicionar uma nova regra de 1 dia para 1 hora.Each PR is independently deployable; the refactor ships as a series of PRs.
Cada PR é independentemente deployable; o refactor sai em uma série de PRs.História
História: Refactoring proposals
Nível: C1
História em inglês
Proposing the user service refactor
On Wednesday, I had to propose a refactor of the user service to the architecture review. I opened with motivation: this module has 7 unrelated responsibilities; SRP suggests splitting it. I delimited the scope: in scope, extract the validation into a helper, split the class in two; out of scope, rename methods, change the persistence layer. I added a safety net: we have 90% test coverage, and we will add characterization tests for the parts that lack coverage. I closed with the expected payoff: after the refactor, the time to add a new validation rule drops from 1 day to 1 hour.
Tradução linha por linha
| Inglês | Tradução |
|---|---|
| On Wednesday, I had to propose a refactor of the user service to the architecture review. | Na quarta, eu tive que propor um refactor do serviço de usuário para a revisão de arquitetura. |
| I opened with motivation: this module has 7 unrelated responsibilities; SRP suggests splitting it. | Eu abri com motivation: este módulo tem 7 responsabilidades não relacionadas; SRP sugere separá-lo. |
| I delimited the scope: in scope, extract the validation into a helper, split the class in two; out of scope, rename methods, change the persistence layer. | Eu delimitei o escopo: dentro, extrair a validação em um helper, separar a classe em duas; fora, renomear métodos, mudar a camada de persistência. |
| I added a safety net: we have 90% test coverage, and we will add characterization tests for the parts that lack coverage. | Eu adicionei uma rede de segurança: temos 90% de cobertura, e vamos adicionar testes de caracterização para as partes sem cobertura. |
| I closed with the expected payoff: after the refactor, the time to add a new validation rule drops from 1 day to 1 hour. | Eu fechei com o ganho esperado: depois do refactor, o tempo para adicionar uma nova regra de validação cai de 1 dia para 1 hora. |
Notas de vocabulário
- 7 unrelated responsibilities; SRP suggests splitting = motivation: princípio + número.
- in scope ... out of scope = scope: delimita o refactor.
- 90% test coverage and characterization tests = safety net: cobertura + characterization.
- time to add a new rule drops from 1 day to 1 hour = payoff mensurável e alinhado ao time.
Perguntas de compreensão
- O que diferencia um refactoring proposal C1?
- O que torna o scope C1 útil?
- O que é safety net em C1?
Prática com a história
- Escreva a motivation C1 para um refactor do user service.
- Escreva o rollout C1 para um refactor em 3 PRs.
- Escreva o safety net C1 para um refactor crítico.
Prática
Exercícios e teste
A próxima melhoria é transformar esses arquivos em perguntas com resposta no navegador. Por enquanto, esta página já organiza o estudo e permite seguir a aula inteira sem abrir os arquivos manualmente.