LSLínguas Sem BenaventeInglês para brasileiros

Aula

Explicar código em pull requests

Nível: B1

Objetivo

Escrever descrições de pull request claras em inglês usando a estrutura What changed, Why it changed, How to test, mencionar trade-offs simples e incluir um checklist de teste com evidência (comandos, saídas esperadas e links) para que o reviewer valide a mudança sem precisar perguntar.

Explicação

Uma boa descrição de pull request (PR) é um mini contrato entre quem propõe a mudança e quem vai revisá-la. Em B1, o padrão recomendado tem três blocos curtos, nesta ordem: What changed, Why it changed e How to test.

What changed — uma ou duas frases no nível de comportamento, sem entrar em detalhes de implementação (esses ficam na diff). Use o presente para descrever o efeito da mudança: *This PR adds a retry cap of 3 attempts to the payment service to prevent runaway retries.* O reviewer entende o que vai ler na diff antes mesmo de abri-la.

Why it changed — a motivação, o ticket ou incidente que originou a mudança e o link para o contexto completo. Use palavras-chave como `Fixes #123` ou `Closes #123` para que o ticket feche automaticamente no merge: *Closes #482, where 1 in 200 charges failed silently during the last bank outage.* Se a escolha não é óbvia, nomeie também a alternativa rejeitada: *We considered a circuit breaker and rejected it because the upstream is rate-limited, not flaky.*

How to test — um checklist com evidência para cada item, não uma promessa vaga. Cada linha traz o comando exato, o resultado esperado e onde ver a evidência: *Run `make test` — all 248 tests pass; see CI run #4182.* Itens manuais seguem o mesmo formato: *Manual check: use the test card `4000 0000 0000 9995` in staging to trigger a 502, and confirm the user sees an error after the third retry.* Itens de carga e cobertura também: *Load test: run `k6 run load/retry.js` and confirm that the worker pool stays below 60% CPU under the failed-bank scenario.*

Trade-offs aparecem quando a decisão tem custo e benefício não óbvios. Em vez de escondê-los em um comentário posterior, nomeie o custo e o benefício na própria descrição: *Trade-off: failed payments are now surfaced to the user after 3 attempts instead of being silently retried in the background.* O reviewer usa essa linha para validar a decisão sem ter que adivinhá-la a partir do código.

Breaking changes ganham uma linha própria no topo, em vez de ficar escondidas em um parágrafo: *Breaking change: the error code for a failed charge changed from `charge_failed` to `charge_retry_exhausted`.* Esse destaque visual protege usuários downstream e ajuda o reviewer a não deixar passar.

Hábitos de apoio que reforçam a estrutura: mantenha o escopo da PR pequeno o suficiente para ser revisado em 15 minutos; prefira screenshots, log snippets ou links de CI a prosa para evidência; e mantenha a terminologia consistente do começo ao fim (se o serviço é `PaymentService`, não troque para `the payment service` no meio do texto).

Exemplos

InglêsTraduçãoObservação
This PR adds a retry cap of 3 attempts to the payment service to prevent runaway retries.Esta PR adiciona um limite de 3 tentativas ao serviço de pagamento para evitar retentativas em loop.Abertura típica de What changed: This PR + verbo no presente + efeito no nível de comportamento.
Closes #482, where 1 in 200 charges failed silently during the last bank outage.Fecha o ticket #482, no qual 1 em cada 200 cobranças falhava silenciosamente durante a última indisponibilidade do banco.A frase cita o ticket (Closes #482) e quantifica o problema.
Trade-off: failed payments are now surfaced to the user after 3 attempts instead of being silently retried in the background.Trade-off: pagamentos com falha agora são exibidos ao usuário após 3 tentativas em vez de ficar retentando silenciosamente em segundo plano.Estrutura clássica de trade-off: custo (exibir ao usuário) e benefício (evitar loop silencioso).
Run `make test` — all 248 tests pass; see CI run #4182.Execute `make test` — todos os 248 testes passam; veja a run #4182 do CI.Item de How to test com comando, resultado esperado e link para a evidência.
Manual check: use the test card `4000 0000 0000 9995` in staging to trigger a 502, and confirm the user sees an error after the third retry.Verificação manual: use o test card `4000 0000 0000 9995` em staging para disparar um 502 e confirme que o usuário vê um erro após a terceira tentativa.Item manual do checklist: rótulo, comando exato e resultado esperado.
Breaking change: the error code for a failed charge changed from `charge_failed` to `charge_retry_exhausted`.Mudança incompatível: o código de erro de uma cobrança com falha mudou de `charge_failed` para `charge_retry_exhausted`.Marcador `Breaking change:` em uma linha própria no topo da PR.
This PR is a refactor with no behavior change; see the diff for the renamed methods.Esta PR é um refactor sem mudança de comportamento; veja a diff para os métodos renomeados.Aviso explícito de refactor: sinaliza ao reviewer que ele não precisa procurar mudança de comportamento.
We considered a circuit breaker and rejected it because the upstream is rate-limited, not flaky.Consideramos um circuit breaker e descartamos a ideia porque o upstream tem rate limit, e não é instável.Alternativa rejeitada com a razão, dentro do bloco Why it changed.

Erros comuns

  • Escrever uma PR com título curto e corpo de uma linha: `Refactored retry helper, should be cleaner now.` — falta contexto e estrutura.
  • Esconder o trade-off em um comentário de follow-up em vez de nomeá-lo na própria descrição da PR.
  • Afirmar `I tested it` sem listar comandos, saídas ou links; o reviewer não consegue reproduzir e tem que confiar na sua palavra.
  • Misturar detalhes de implementação na seção What changed; o que importa nessa seção é o efeito no comportamento, não a estrutura do código.
  • Escrever a breaking change dentro de um parágrafo de Why em vez de em uma linha própria `Breaking change:`, que se perde na leitura.
  • Pular o link para o ticket e obrigar o reviewer a abrir o Jira/GitHub para descobrir do que se trata a PR.
  • Marcar a PR como `ready for review` antes de o checklist de How to test estar completo, deixando o reviewer testar no escuro.

Prática guiada

Transforme esta descrição vaga em uma PR com a estrutura recomendada:

> `Refactored cache stuff, also fixed a thing. Tested locally, should work.`

Versão reescrita:

  • What changed: This PR replaces the in-memory cache with a 5-minute TTL LRU cache and adds a new `cache_stats` endpoint that returns the current hit ratio and miss count.
  • Why it changed: Closes #210, where stale entries caused wrong totals on the dashboard. Trade-off: a 5-minute window of staleness in exchange for predictable cache size.
  • How to test:
  • `make test` — all 142 tests pass; see CI run #3810.
  • Manual check: write a value, wait 6 minutes, hit `/dashboard`, and confirm the fresh value appears.
  • Open `/cache_stats` in staging and confirm `hit_ratio` is above 0.4 in the staging logs.

Observe o que mudou: a estrutura em três blocos substitui a frase vaga; o ticket (#210) está linkado com `Closes`; o trade-off está explícito; e cada item de How to test traz comando e evidência verificável. A mesma informação, em um formato que o reviewer consegue validar em minutos.

Resumo

Uma boa descrição de PR tem três blocos: What changed (efeito no comportamento), Why it changed (motivação, ticket e trade-off) e How to test (checklist com comandos, saídas e links para evidência). Marcadores como `Fixes #` e `Breaking change:` aceleram o review e protegem usuários downstream.

Vocabulário

Palavras principais

18 itens
pull requestsolicitação de merge, pull request

Please open a pull request with a clear description.

Abra um pull request com uma descrição clara.
changealteração, mudança

This change updates the retry helper.

Esta alteração atualiza o helper de retentativas.
trade-offtrade-off, compensação

There's a small trade-off between speed and memory.

Há um pequeno trade-off entre velocidade e memória.
evidenceevidência, comprovação

Each checklist item must include evidence.

Cada item do checklist deve incluir evidência.
checklistlista de verificação, checklist

Add a test checklist before requesting review.

Adicione um checklist de teste antes de pedir review.
ticketticket, chamado

Link the ticket in the PR description.

Linke o ticket na descrição da PR.
breaking changemudança incompatível

Mark the breaking change with its own line.

Marque a breaking change com sua própria linha.
scopeescopo

Keep the scope of the PR small.

Mantenha o escopo da PR pequeno.
reviewerrevisor, reviewer

The reviewer should be able to test without asking questions.

O reviewer deve conseguir testar sem fazer perguntas.
branchbranch, ramo

Open the PR from a feature branch.

Abra a PR a partir de uma feature branch.
commitcommit

Squash the commits before merging.

Faça squash dos commits antes de mesclar.
diffdiff, diferenças

Read the diff carefully before approving.

Leia a diff com atenção antes de aprovar.
regressionregressão

This change prevents a regression we saw last month.

Esta alteração previne uma regressão que vimos no mês passado.
refactorrefatorar; refactor

This PR is a refactor with no behavior change.

Esta PR é um refactor sem mudança de comportamento.
fixcorrigir; correção

The PR fixes a bug in the retry helper.

A PR corrige um bug no helper de retentativas.
behaviorcomportamento

The new behavior matches the old behavior under normal load.

O novo comportamento combina com o antigo sob carga normal.
rationalejustificativa, rationale

State the rationale for the change.

Apresente a justificativa para a mudança.
alternativealternativa

We considered an alternative and rejected it because of the rate limit.

Consideramos uma alternativa e a rejeitamos por causa do rate limit.

História

História: Explicar código em pull requests

Nível: B1

História em inglês

A pull request nobody wanted to review

On Monday morning, Sofia pushed a new branch and opened a pull request to refactor the retry layer in the payment service. The title was short: "Cleanup in payments retry". The description was even shorter: "Refactored the retry helper. Should be cleaner now." Mark, the senior engineer on call for code review, opened the PR and frowned at the screen. He could not tell what behavior had changed, why the refactor was needed, or how to test it. He left a one-line comment: "Please add a proper description. I can't review what I don't understand." Sofia stared at the comment and opened her team's PR template.

Sofia rewrites the description

The template had three sections: What changed, Why it changed, and How to test. Under "What changed", she wrote: "This PR adds a max-attempts cap of 3 to the payment retry helper and surfaces the final error to the user." Under "Why it changed", she explained: "Closes #482. Without a cap, the service retried 502s forever during the last bank outage and saturated the worker pool." She also called out the trade-off: "Trade-off: a failed payment is now surfaced to the user after 3 attempts instead of being silently retried in the background. We accept that to protect the worker pool." At the top of the description, she added a `Breaking change:` line: "Breaking change: the error code for a failed charge changed from `charge_failed` to `charge_retry_exhausted`." Under "How to test", she added a checklist with evidence for each step. The first item read: "Run `make test` — all 248 tests pass; see CI run #4182." The second item read: "Manual check: trigger a 502 in staging using the test card `4000 0000 0000 9995` and confirm the user sees an error after the third attempt." The third item read: "Load test: run `k6 run load/retry.js` and confirm that the worker pool stays below 60% CPU under the failed-bank scenario."

Mark goes through the checklist

On Tuesday morning, Mark opened the pull request again and read the new description. He noticed the `Fixes #482` link and clicked through to the incident report. He then ran `make test` on his local machine, and all 248 tests passed in 41 seconds. For the manual check, he used the same test card and confirmed the user saw a clear error message after the third retry. He also ran the load test, and the worker pool stayed at 52% CPU, which was well below the 60% cap. Mark noticed that the old version had no max-attempts cap, so the new behavior matched the trade-off Sofia had described. He left one small comment about renaming `RetryPolicy` to `RetryBudget`, since the team already had a class with that name. Sofia renamed the class, pushed the change, and re-requested review; Mark approved the pull request, and the new behavior went live the same afternoon.

Tradução linha por linha

InglêsTradução
On Monday morning, Sofia pushed a new branch and opened a pull request to refactor the retry layer in the payment service.Na segunda-feira de manhã, Sofia enviou uma nova branch e abriu um pull request para refatorar a camada de retentativas do serviço de pagamento.
The title was short: "Cleanup in payments retry".O título era curto: "Cleanup in payments retry".
The description was even shorter: "Refactored the retry helper. Should be cleaner now."A descrição era ainda mais curta: "Refactored the retry helper. Should be cleaner now."
Mark, the senior engineer on call for code review, opened the PR and frowned at the screen.Mark, o engenheiro sênior escalado para o code review, abriu a PR e fez uma careta para a tela.
He could not tell what behavior had changed, why the refactor was needed, or how to test it.Ele não conseguia dizer qual comportamento tinha mudado, por que o refactor era necessário ou como testá-lo.
He left a one-line comment: "Please add a proper description. I can't review what I don't understand."Ele deixou um comentário de uma linha: "Please add a proper description. I can't review what I don't understand."
Sofia stared at the comment and opened her team's PR template.Sofia encarou o comentário e abriu o template de PR do time dela.
The template had three sections: What changed, Why it changed, and How to test.O template tinha três seções: What changed, Why it changed e How to test.
Under "What changed", she wrote: "This PR adds a max-attempts cap of 3 to the payment retry helper and surfaces the final error to the user."Em "What changed", ela escreveu: "This PR adds a max-attempts cap of 3 to the payment retry helper and surfaces the final error to the user."
Under "Why it changed", she explained: "Closes #482. Without a cap, the service retried 502s forever during the last bank outage and saturated the worker pool."Em "Why it changed", ela explicou: "Closes #482. Without a cap, the service retried 502s forever during the last bank outage and saturated the worker pool."
She also called out the trade-off: "Trade-off: a failed payment is now surfaced to the user after 3 attempts instead of being silently retried in the background. We accept that to protect the worker pool."Ela também apontou o trade-off: "Trade-off: a failed payment is now surfaced to the user after 3 attempts instead of being silently retried in the background. We accept that to protect the worker pool."
At the top of the description, she added a `Breaking change:` line: "Breaking change: the error code for a failed charge changed from `charge_failed` to `charge_retry_exhausted`."No topo da descrição, ela adicionou uma linha `Breaking change:`: "Breaking change: the error code for a failed charge changed from `charge_failed` to `charge_retry_exhausted`."
Under "How to test", she added a checklist with evidence for each step.Em "How to test", ela adicionou um checklist com evidência para cada passo.
The first item read: "Run `make test` — all 248 tests pass; see CI run #4182."O primeiro item dizia: "Run `make test` — all 248 tests pass; see CI run #4182."
The second item read: "Manual check: trigger a 502 in staging using the test card `4000 0000 0000 9995` and confirm the user sees an error after the third attempt."O segundo item dizia: "Manual check: trigger a 502 in staging using the test card `4000 0000 0000 9995` and confirm the user sees an error after the third attempt."
The third item read: "Load test: run `k6 run load/retry.js` and confirm that the worker pool stays below 60% CPU under the failed-bank scenario."O terceiro item dizia: "Load test: run `k6 run load/retry.js` and confirm that the worker pool stays below 60% CPU under the failed-bank scenario."
On Tuesday morning, Mark opened the pull request again and read the new description.Na terça-feira de manhã, Mark abriu o pull request de novo e leu a nova descrição.
He noticed the `Fixes #482` link and clicked through to the incident report.Ele notou o link `Fixes #482` e clicou até o relatório do incidente.
He then ran `make test` on his local machine, and all 248 tests passed in 41 seconds.Em seguida, ele rodou `make test` na máquina local, e todos os 248 testes passaram em 41 segundos.
For the manual check, he used the same test card and confirmed the user saw a clear error message after the third retry.Para a verificação manual, ele usou o mesmo test card e confirmou que o usuário viu uma mensagem de erro clara após a terceira retentativa.
He also ran the load test, and the worker pool stayed at 52% CPU, which was well below the 60% cap.Ele também rodou o load test, e o worker pool ficou em 52% de CPU, bem abaixo do limite de 60%.
Mark noticed that the old version had no max-attempts cap, so the new behavior matched the trade-off Sofia had described.Mark percebeu que a versão antiga não tinha limite de tentativas, então o novo comportamento batia com o trade-off que Sofia tinha descrito.
He left one small comment about renaming `RetryPolicy` to `RetryBudget`, since the team already had a class with that name.Ele deixou um comentário pequeno sobre renomear `RetryPolicy` para `RetryBudget`, porque o time já tinha uma classe com esse nome.
Sofia renamed the class, pushed the change, and re-requested review; Mark approved the pull request, and the new behavior went live the same afternoon.Sofia renomeou a classe, enviou a alteração e pediu review de novo; Mark aprovou o pull request, e o novo comportamento entrou no ar na mesma tarde.

Notas de vocabulário

  • pull request = solicitação de merge; espaço de revisão de código e de discussão de mudanças
  • What changed = primeiro bloco da PR; descreve o efeito no comportamento em uma ou duas frases
  • Why it changed = segundo bloco; motivação, link para o ticket e o problema que originou a mudança
  • How to test = terceiro bloco; checklist com comandos, saídas e links para evidência
  • Trade-off = linha curta que nomeia custo e benefício de uma decisão não óbvia
  • Breaking change = rótulo em uma linha própria para sinalizar mudanças incompatíveis com versões anteriores
  • CI run = execução do pipeline de CI; onde o reviewer consulta a evidência dos testes automatizados
  • test card = cartão de pagamento usado em ambiente de teste para disparar respostas específicas (ex.: 502)

Perguntas de compreensão

  1. What was the problem with Sofia's first PR description?
  2. What three sections did Sofia's PR template have?
  3. Which ticket did Sofia's new description link to?
  4. What trade-off did Sofia mention in the PR description?
  5. How did Mark verify the first item in the How to test checklist?
  6. What test card did Mark use for the manual check?
  7. Why did the worker pool stay below 60% CPU during the load test?
  8. What small change did Mark request before approving the PR?

Prática com a história

  1. Rewrite this vague PR description as a proper three-block structure: 'Updated cache. Should work. Tested locally.'
  2. Translate: 'Esta PR é um refactor e não altera o comportamento da API.'
  3. Fill in: 'The PR ___ a race condition in the cache layer that caused stale reads.'
  4. Write a How-to-test bullet for a bug fix in the login flow, where the bug appears when a user signs in with an empty password.
  5. Classify the following sentence: 'Trade-off: average latency increases from 30ms to 70ms in exchange for not losing charges on upstream failures.'

Prática

Exercícios e teste

Próxima etapa
8blocos de exercícios disponíveis neste tema
10questões de teste para revisar depois da aula

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.