Yeda AI Tips · #102

Español

Big Refactor? Write a Codemod, Not Hand Edits

Once a refactor touches hundreds of lines, stop hand-editing. Manual edits at that scale are error-prone and exhausting to review: you will miss cases, and your reviewers can't trust a 500-line diff of "the same change, probably, everywhere." Write the transform instead — a codemod, a sed script, or an AST rewrite — and the change becomes mechanical, uniform, and reviewable.

Why hand edits break down at scale

A refactor like "rename this API," "swap this import," or "change this call signature" is one decision applied N times. When N is 5, your editor is fine. When N is 500:

A scripted transform inverts all three: coverage is whatever your pattern matches, every change is identical by construction, and the reviewer reads the ~20-line transform, not the 500-line output.

Pick the lightest tool that's still correct

Change looks likeReach forWhy
Exact string, no syntax risksed / editor multi-file replaceFastest; fine when a false match is impossible
Pattern with balanced brackets, many languagesCombyStructural match without writing parser code
Syntax-aware find/replace, one-linerast-grepPattern + rewrite on the AST, from the CLI
JS/TS transform with logicjscodeshiftFull programmatic AST access, preserves style via recast
Python transform preserving comments/formatLibCST codemodsLossless concrete syntax tree
Java/JVM framework migrationOpenRewritePrepackaged recipes over lossless semantic trees

Rule of thumb: escalate only when the simpler tool can produce a false match. Text → structural pattern → full AST program.

What it looks like

Syntax-aware one-liner with ast-grep — rewrite var declarations to let across a TypeScript repo:

ast-grep --pattern 'var code = $PATTERN' \
         --rewrite 'let code = new $PATTERN' \
         --lang ts

When you need logic, a jscodeshift transform is a small JS function; run it with a dry pass first:

jscodeshift -t rename-api.js src/ --dry --print   # preview
jscodeshift -t rename-api.js src/                 # apply

Either way, the artifact you commit alongside the diff is the transform. That's what gets reviewed.

The payoff for review

Ship the refactor as two things: the script, and one commit that is purely its output. The reviewer checks the rule once, spot-checks a few applications, and trusts the rest — because a machine applied one rule uniformly. That's a fundamentally stronger guarantee than 500 careful keystrokes, and it's re-runnable when the branch goes stale: rebase, re-run the codemod, done.

Power-user moves

Resources

Building an AI feature? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog