Code Refactoring Without AI
You've probably used ChatGPT or Claude to refactor code. It's powerful for complex changes—extracting functions, restructuring architecture, or applying design patterns. But for simple, everyday improvements? Your IDE is faster, more accurate, and already knows your entire codebase.
Think of it this way: You don't use a chainsaw to trim your fingernails. Similarly, you don't need an LLM to rename a variable or fix indentation. This guide teaches you when to reach for the right tool.
What You'll Learn
This guide covers two complementary areas so you can work faster and safer:
- 20 core refactoring techniques to improve code structure without AI (renaming, cleanup, strings, structure/logic, etc.).
- 25 essential editor macros to automate repetitive typing and formatting (text editing, cleaning, boilerplate, and multi‑step chains).
Before we start, make sure you've configured auto-formatting in your editor. It's the single most important productivity boost for any developer. If you haven't done this yet, skip to the FAQ section and set it up now—it takes 2 minutes.
⚡ Editor Macros & Snippets
These pragmatic, editor-native automations eliminate repetitive keystrokes. Use them for fast text edits, consistent formatting, boilerplate insertion, and chained multi-step actions.
Text Editing Macros — Interactive Cards
Convert Selection to Uppercase
Instantly turn highlighted text into ALL CAPS for constants, headings, or callouts.
Click to see how
How to Uppercase Selection
- Select text.
- Run command: Transform to Uppercase.
- VS Code / Cursor: Command Palette →
Transform to Uppercase. - Bind to a hotkey in
keybindings.jsonfor 1‑tap use.
Convert Selection to Lowercase
Normalize text to lowercase for case‑insensitive comparisons and slugs.
Click to see how
How to Lowercase Selection
- Select text → Transform to Lowercase.
- VS Code / Cursor: Command Palette →
Transform to Lowercase.
Convert Selection to Title Case
Apply Title Case to headings and commit subjects for readable, consistent style.
Click to see how
How to Title‑Case
- Select text → Run Title Case extension/macro.
- Use a lightweight extension such as
Title Caseand bind a key.
Wrap Selection
Quickly surround selection with () { } [ ] "" '' using one hotkey.
Click to see how
How to Wrap
- Select text → Command Palette →
Emmet: Wrap with Abbreviation. - Type the wrapper, e.g.
( $TM_SELECTED_TEXT ).
- VS Code / Cursor: Emmet wrap; create a macro for common pairs.
Duplicate Line/Selection Down
Copy the active line or selection and paste immediately below.
Click to see how
Duplicate Down
- VS Code / Cursor:
Shift+Alt+Down(Win/Linux),Shift+Option+Down(Mac).
Duplicate Line/Selection Up
Paste the duplicate immediately above the current line/selection.
Click to see how
Duplicate Up
- VS Code / Cursor:
Shift+Alt+Up(Win/Linux),Shift+Option+Up(Mac).
Delete Current Line
Remove the entire line where the cursor is—no selection needed.
Click to see how
Delete Line
- VS Code / Cursor:
Ctrl+Shift+K(Win/Linux),Cmd+Shift+K(Mac).
Join Lines
Merge the next line into the current one, removing the break cleanly.
Click to see how
Join Lines
- VS Code / Cursor: Command Palette →
Join Lines.
Add Cursors to Line Ends
Batch‑edit multiple lines by placing a cursor at each selected line end.
Click to see how
Multi‑Cursor Line Ends
- Select lines →
Add Cursors to Line Ends.
- VS Code / Cursor: Command Palette →
Add Cursors to Line Ends.
Select All Occurrences
Select a word, then select every other instance of that word in the file.
Click to see how
Select All Occurrences
- VS Code / Cursor:
Ctrl+F2(Win/Linux),Cmd+Ctrl+G(Mac).
🧹 Code Formatting & Cleaning — Interactive Cards
Format Document
Apply the project's formatter/linter rules to the entire file.
Click to see how
Format Document
- VS Code / Cursor:
Shift+Alt+F(Win/Linux),Shift+Option+F(Mac).
Format Selection
Format only the highlighted block—great for staged changes.
Click to see how
Format Selection
- VS Code / Cursor: Command Palette →
Format Selection.
Trim Trailing Whitespace
Remove invisible end-of-line whitespace across the file.
Click to see how
Trim Whitespace
- VS Code / Cursor:
files.trimTrailingWhitespace: true. - Optional: add as a command to trigger on demand.
Insert Final Newline
Ensure the file ends with a POSIX‑friendly newline.
Click to see how
Final Newline
- VS Code / Cursor:
files.insertFinalNewline: true.
Fix All Linting Errors
Run the linter’s auto‑fix for quick wins before commit.
Click to see how
Fix All
- VS Code / Cursor: Command Palette →
ESLint: Fix all auto-fixable Problems. - CLI:
eslint --fixon the file or project.
🏗️ Code Insertion & Boilerplate — Interactive Cards
Insert console.log
Type clg and expand to console.log($1); with cursor inside.
Click to see how
Snippet: console.log
- VS Code / Cursor user snippet:
console.log(${"$1"}); - Trigger:
clg.
Insert log‑variable
Wrap a variable: console.log('myVar:', myVar); for quick inspection.
Click to see how
Snippet: log variable
console.log('${"$TM_SELECTED_TEXT"}:', ${"$TM_SELECTED_TEXT"});- Select a token first to auto‑wrap.
Insert HTML5 Boilerplate
Use ! to create a complete HTML scaffold in new files.
Click to see how
Emmet: HTML5
- New
.htmlfile → type!→ pressTab.
Insert Function/Component
Use a snippet like rafce to scaffold a React component instantly.
Click to see how
Snippet: Component
- Install React snippets or create a custom snippet for your team template.
Insert Loop
Use forof to expand a typed loop with placeholders.
Click to see how
Snippet: for..of
for (const ${"$1"} of ${"$2"}) {\n ${"$0"}\n}
🏃 Multi‑Step Command Sequences — Interactive Cards
Save and Format
One key to save then format document. Perfect for pre‑commit polish.
Click to see how
Command Chain
- In
keybindings.json, chainworkbench.action.files.savetheneditor.action.formatDocument.
“Log and Move” for Debugging
Insert console.log('HERE'); on a new line, then return to origin.
Click to see how
Command Chain
- Chain: Insert Line Below → Insert Snippet → Cursor Undo.
- Snippet body:
console.log('HERE');
Duplicate and Comment Out
Clone a line then comment out the original to experiment safely.
Click to see how
Command Chain
- Duplicate line down → Toggle Line Comment on previous line.
Open File and Split View
Open a related file (e.g., tests) and move it to a split editor pane.
Click to see how
Command Chain
- Chain: Quick Open → Focus Right Group → Move Editor Right.
Run Build & Toggle Panel
Execute the build task and reveal the output/terminal in one keystroke.
Click to see how
Command Chain
- Chain: Run Task (e.g.,
npm run build) → Toggle Panel.
🏷️ Naming & Identity
Ever spent 10 minutes doing find-and-replace across a file, only to miss three references and break your code? That's what we're fixing here.
Variable and function names matter more than you think. A well-named constant makes code self-documenting. A poorly-named loop variable creates confusion that cascades through code reviews and debugging sessions.
These four tasks help you rename things safely—across your entire project if needed—without the risk of breaking references.
Rename a Variable
Change a variable name and automatically update all references in the current scope. Your IDE finds every usage—even in nested functions or closures—and updates them atomically.
Click to see how
How to Rename a Variable
- Place cursor on the variable name anywhere it appears
- Press F2 (VS Code) or Shift+F6 (IntelliJ/WebStorm)
- Type the new name
- Press Enter—all references update instantly
- VS Code:
F2or Right-click → Rename Symbol - IntelliJ/WebStorm/PyCharm:
Shift+F6 - Most modern IDEs support this natively
- Works across entire file or project scope automatically
- Preview changes before applying if you're nervous
- Choose descriptive names:
userDatabeatsx
Rename a Function
Update function names across your codebase, including all call sites. Critical for public APIs where a single missed reference could break production.
Click to see how
How to Rename a Function
- Click on the function name (definition or any usage)
- Use the same rename shortcut: F2 or Shift+F6
- IDE searches for all invocations across files
- Type new name—updates propagate everywhere
- Same shortcuts as variable rename—muscle memory wins
- Works for methods, classes, interfaces too
- Check for method overloads—they need special attention
- Be cautious with exported/public functions—external code may depend on them
- Run tests immediately after renaming
- Use version control to easily revert if something breaks
Replace Magic Numbers
See 86400 in your code and have no idea what it means? Convert mysterious numbers into named constants like SECONDS_PER_DAY.
Click to see how
How to Replace Magic Numbers
- Find the unexplained number in your code
- Create a named constant at the top of your file or class
- Use Find & Replace (Ctrl+H) to swap all occurrences
- Test to ensure the meaning hasn't changed
- Manual:
Ctrl+H(Find & Replace) - Some IDEs: "Extract Constant" refactor command
- Search carefully—context matters for numbers
- Use UPPER_SNAKE_CASE for constants by convention
- Group related constants together for organization
- Example:
MAX_RETRIES = 3is self-explanatory
Rename Loop Variables
Replace generic i with meaningful names like userIndex. Makes nested loops readable and prevents off-by-one errors.
Click to see how
How to Rename Loop Variables
- Select the loop variable in its declaration
- Use F2 or manual find-replace within the loop block
- Ensure the scope is limited to just this loop
- Verify no outer scope conflicts
- F2 works best—it's scope-aware automatically
- Multi-cursor editing:
Ctrl+Din VS Code - Check that only loop references change
- Nested loops: avoid i, j, k—use
rowIndex, colIndex - Modern style: prefer
for item in itemswhen possible - Descriptive names prevent bugs in complex iterations
Example: Magic Numbers in Action
Here's what happens when you don't use named constants. The first version leaves readers guessing. The second version documents itself.
❌ Before: Mysterious Numbers
What do these numbers mean? Why 100? Why 0.85?
function calculatePrice(qty) { if (qty > 100) { return qty * 9.99 * 0.85; } return qty * 9.99; }
✅ After: Self-Documenting Code
The code explains itself. Future you will be grateful.
const UNIT_PRICE = 9.99; const BULK_THRESHOLD = 100; const BULK_DISCOUNT = 0.85; function calculatePrice(qty) { if (qty > BULK_THRESHOLD) { return qty * UNIT_PRICE * BULK_DISCOUNT; } return qty * UNIT_PRICE; }
📝 Code Cleanup & Formatting
Technical debt accumulates slowly. A commented-out function here. An unused import there. Six months later, your file is a archaeological dig site.
These cleanup tasks remove cruft automatically. Most take under 5 seconds to execute, and they make your code dramatically easier to read and maintain.
Fix Indentation
One keyboard shortcut fixes every spacing issue in your file. Works after copy-pasting code or merging branches with different styles.
Click to see how
How to Fix Indentation
- Open the file with messy indentation
- Press Shift+Alt+F (Windows) or Shift+Option+F (Mac)
- Formatter applies consistent rules across entire file
- Save—you're done
- VS Code:
Shift+Alt+For "Format Document" - Prettier, ESLint with
--fix - Language-specific: Black (Python), gofmt (Go)
- Enable "Format on Save" in settings—never think about it again
- Configure rules in project config for team consistency
- Use EditorConfig to sync settings across editors
Delete Commented Code
That "just in case" code block you commented out 6 months ago? Delete it. Version control is your safety net.
Click to see how
How to Delete Commented Code
- Search for comment patterns:
//or/* - Review each commented block carefully
- Delete if it's genuinely unused code
- Keep only meaningful documentation comments
- Manual: Multi-line selection + Delete key
- Regex search for specific patterns
- Some linters flag commented code as warnings
- If you need it later, use Git to retrieve it
- Keep TODO comments with ticket numbers and dates
- Remove debug print statements too
Remove Unused Imports
Your IDE grays out unused imports automatically. One command removes them all. Cleaner code, smaller bundles.
Click to see how
How to Remove Unused Imports
- IDE highlights unused imports (grayed out text)
- Press Ctrl+Shift+O (VS Code) or Ctrl+Alt+O (IntelliJ)
- Command removes unused, sorts alphabetically
- Done—file is cleaner instantly
- VS Code:
Ctrl+Shift+Oor "Organize Imports" - ESLint:
no-unused-varsrule with --fix - IntelliJ:
Ctrl+Alt+O
- Run before committing code—good habit
- Catches refactoring mistakes early
- Reduces bundle size in frontend applications
Delete Unused Variables
Declared but never used? Your linter knows. Delete it before someone wastes time wondering why it exists.
Click to see how
How to Delete Unused Variables
- Look for grayed-out or underlined variable names
- Verify it's truly unused (check all scopes)
- Delete the declaration line
- Run linter to confirm no warnings remain
- ESLint:
no-unused-varswith --fix flag - IDE warnings and hints (hover to see)
- TypeScript compiler errors catch these
- Be careful with side-effect assignments
- Unused function params: prefix with underscore
_param - Clean code = fewer bugs lurking
Delete Unused Functions
Functions that are never called waste mental energy. Use "Find All References" to verify, then delete confidently.
Click to see how
How to Delete Unused Functions
- Right-click function name → Find All References
- If only the definition shows up (no calls), it's safe to delete
- Check tests too—might be tested but unused in production
- Delete both function and its tests
- IDE: Right-click → Find All References
- ESLint with --fix (limited support)
- Dead code detection tools for large projects
- Cautious with exported/public functions—external code may use them
- Check if used dynamically (string-based calls)
- Git history preserves deleted code if needed later
Reformat Entire File
Applies every code style rule in one shot. Quotes, semicolons, line breaks—all consistent instantly.
Click to see how
How to Reformat a File
- Open file that needs formatting
- Same as "Fix Indentation" but more comprehensive
- Formatter applies all configured style rules
- Can reformat selection or entire project
- Prettier:
prettier --write . - ESLint:
eslint --fix src/ - IDE: Format Document command
- Set up pre-commit hooks to auto-format before commits
- Choose one formatter per project to avoid conflicts
- Document style choices in README or CONTRIBUTING.md
🔡 Strings & Literals
Keep strings intentional and portable. These tasks reduce duplication, prepare code for i18n, and enforce consistent style.
Extract Hardcoded String
Replace magic text with a named constant or i18n key to avoid duplication and enable translation.
Click to see how
How to Extract a String
- Locate repeated/important string literal.
- Create a constant or localization entry.
- Find & replace usages with the new identifier.
- Refactor: Extract Constant (where supported)
- Find & Replace across project
- Prefer constants module or i18n file for discoverability.
- Avoid leaking UI strings into business logic.
Replace Quotes
Standardize on single or double quotes using your formatter to reduce churn in diffs.
Click to see how
How to Standardize Quotes
- Prettier:
singleQuote(true/false) - Format document to apply consistently
- Pick one style per project; document it.
- Run on save to avoid style-only diffs.
Merge String Literals
Combine adjacent string pieces into a single literal/template for clarity.
Click to see how
How to Merge Literals
- Join adjacent pieces into one string or template literal.
- Keep interpolation clear and minimal.
- Prefer template literals for multi‑value composition.
Change Constant Value
Update a constant and verify intent across usages to avoid subtle behavior shifts.
Click to see how
How to Update a Constant
- Edit the constant definition.
- Search references; confirm the new value remains correct.
- Run tests or quick checks where value matters.
🔩 Structure & Logic
Make code easier to read, test, and maintain by improving structure and simplifying logic flows.
Split Long Line
Break long expressions at logical boundaries so code wraps cleanly and reads well.
Click to see how
How to Split Lines
- Break after commas or operators.
- Indent continuation lines for clarity.
Simplify Expressions
Remove redundant operations: x + 0 → x, y * 1 → y, unnecessary double negations, etc.
Click to see how
How to Simplify
- Scan for neutral operations and remove them.
- Prefer direct expressions over nested conditionals.
Inline Variable
Replace a one‑time variable with its value to reduce indirection and mental load.
Click to see how
How to Inline
- IntelliJ: Inline Variable
- Manual: Replace then delete declaration
- Only inline when it truly increases clarity.
Reorder Parameters
Place required parameters first, optional later, and propagate changes to all call sites.
Click to see how
How to Reorder
- Change function signature.
- Find all references; update call sites accordingly.
- Run tests for behavior regressions.
Move File
Relocate modules the IDE way so imports update automatically and history is preserved.
Click to see how
How to Move
- Use IDE move/drag; verify updated import paths.
- With Git, prefer
git mvto retain history.
Add/Update Docstring
Document purpose, inputs, and outputs. Future readers will thank you.
Click to see how
How to Document
- JS/TS: type
/**then Enter to scaffold. - Describe purpose, params, return types clearly.
Example: Dead Code Clutter
Compare these two files. The first has commented code and unused imports. The second is clean, focused, and ready for production.
❌ Before: Messy Imports
Commented code, unused imports—hard to scan.
import React from 'react'; import { useState, useEffect } from 'react'; import lodash from 'lodash'; // unused // function oldImplementation() { // return fetchData(); // } function App() { const [data, setData] = useState(null); // render... }
✅ After: Clean and Focused
Only what's needed. Easier to read, faster to understand.
import React, { useState } from 'react'; function App() { const [data, setData] = useState(null); // render... }
🔄 Quick Reference
All 20 tasks in one place. The first column stays fixed when you scroll horizontally—especially useful on mobile devices.
| Task | Process | Tool / Shortcut | Tips |
|---|---|---|---|
| Rename variable | Right-click or F2 → Rename | VS Code: F2, IntelliJ: Shift+F6 | Updates all references automatically |
| Rename function/method | Right-click or F2 → Rename | F2 or Shift+F6 | Watch for overloads/exports |
| Replace magic number | Create constant, use find-replace | Ctrl+H (Find & Replace) | Use descriptive constant names |
| Rename loop variable | F2 on variable in loop | F2, Shift+F6 | Use descriptive names in nested loops |
| Fix indentation | Format document command | Shift+Alt+F (VS Code) | Enable format-on-save |
| Remove commented code | Search and delete manually | Find // or /* |
Trust version control |
| Delete unused imports | Organize imports command | Ctrl+Shift+O (VS Code) | Run before every commit |
| Delete unused variables | Find grayed-out vars, delete | ESLint --fix, IDE hints | Prefix unused params with _ |
| Delete unused functions | Find All References, delete | Right-click → Find References | Check for dynamic calls first |
| Reformat file | Run formatter on entire file | Prettier, ESLint --fix | Set up pre-commit hooks |
| Extract hardcoded string | Create constant, replace all | Ctrl+H (Find & Replace) | Prepares code for i18n |
| Replace quotes | Configure formatter rules | Prettier singleQuote setting | Pick one style per project |
| Merge string literals | Combine adjacent strings | Manual editing | Watch for escape characters |
| Change constant value | Edit value, grep usages | Find All References | Verify intent across codebase |
| Split long line | Insert break at logical point | Enter key + manual indent | Break after commas in args |
| Simplify expressions | Remove redundant operations | Manual editing | x + 0 becomes x, y * 1 becomes y |
| Inline variable | Replace with value, delete | IntelliJ: Inline Variable | Only if used once and clear |
| Reorder parameters | Change signature + all calls | Find All References | Required params before optional |
| Move file | Drag-drop in file explorer | IDE updates imports automatically | Use git mv to preserve history |
| Add/update docstring | Type doc comment above function | Type /** + Enter (JS/TS) |
Describe purpose, params, return |
🧪 Quick Quiz
Test your knowledge
👩💻 Build Your First Macro
Create a real multi‑step macro using VS Code/Cursor keybindings.json. This example duplicates the current line, moves the cursor back up, and comments out the original.
- Open Command Palette → Preferences: Open Keyboard Shortcuts (JSON).
- Add the following object to the array and save.
// In VS Code or Cursor, open "Preferences: Open Keyboard Shortcuts (JSON)"
// Add this to the array:
{
"key": "ctrl+alt+d", // or choose your preferred shortcut
"command": "runCommands",
"args": {
"commands": [
"editor.action.copyLinesDownAction",
"editor.action.moveLinesUpAction",
"editor.action.addCommentLine"
]
},
"when": "editorTextFocus && !editorReadonly"
}
Tip: On macOS you can use cmd+alt+d or any free chord. You can create more chains the same way (e.g., Save → Format → Toggle Panel).
Macro 2 — Save and Format
One key to save the file and then apply your formatter.
{
"key": "ctrl+alt+s",
"command": "runCommands",
"args": {
"commands": [
"workbench.action.files.save",
"editor.action.formatDocument"
]
},
"when": "editorTextFocus && !editorReadonly"
}
Macro 3 — Run Build & Toggle Panel
Kick off your default build task and reveal the output panel.
{
"key": "ctrl+alt+b",
"command": "runCommands",
"args": {
"commands": [
"workbench.action.tasks.build",
"workbench.action.togglePanel"
]
},
"when": "editorTextFocus && !editorReadonly"
}
When to use which macro?
- Duplicate & Comment Out: When you want to try a new line or small refactor but keep the original for reference. Great during risky edits and debugging.
- Save & Format: Before staging/committing, or anytime you paste code and want instant style conformity. Helps avoid noise in diffs.
- Run Build & Toggle Panel: For quick feedback loops while iterating on code, especially when you want the output/terminal to pop open automatically.
🧪 Macro Quiz
Which macro fits the situation?
❔ Frequently Asked Questions
Common questions about when to use manual refactoring versus AI tools, plus setup tips to maximize your productivity.
Beyond the 20 main tasks, here are 15 more mechanical refactorings your IDE can handle:
- Change access modifiers: Switch private/public/protected—just update the keyword and verify usages.
- Add/remove blank lines: Improves visual grouping. Most formatters handle this automatically.
- Convert single-line if to multi-line: Expand
if (x) return y;to block style for consistency. - Sort imports alphabetically: Use "Organize Imports" command for instant alphabetization.
- Collapse nested ifs: Simplify
if (a) { if (b) {} }toif (a && b) {}when logical. - Convert tabs to spaces: Single editor command or setting handles project-wide conversion.
- Reorder class members: Drag-drop methods/properties for better logical grouping.
- Fix typos in comments: Simple text edit that improves documentation quality.
- Switch for to forEach: Modern syntax when array structure is simple.
- Use spread operator: Replace manual array operations with cleaner
[...arr]syntax. - Remove unnecessary escapes: Clean up strings like
"don\'t"when using proper quotes. - Convert var to let/const: Modern JavaScript—
letfor mutable,constfor immutable. - Add trailing commas: Cleaner git diffs, easier to add items later.
- Remove redundant parentheses:
return (x);simplifies toreturn x; - Convert to arrow functions:
function() {}becomes() => {}when appropriate.
Use AI when the refactoring requires understanding the "why" behind your code, not just the "what." Specifically:
- Architectural changes: Applying design patterns, restructuring module boundaries, separating concerns.
- Complex extractions: Breaking large functions into well-named smaller ones with clear responsibilities.
- Logic transformations: Converting imperative to functional style, optimizing algorithms.
- Cross-file coordination: Changes spanning many files with complex interdependencies.
- Test generation: Writing comprehensive test cases for refactored code.
- Documentation: Generating detailed API docs or explaining complex logic.
Simple rule: If it's mechanical and your IDE has a button for it, don't use AI. If it requires judgment about business logic or architecture, AI excels.
Set up these essentials to make refactoring effortless:
Code Formatter
- JavaScript/TypeScript: Prettier
- Python: Black or autopep8
- Go: gofmt (built-in)
- Rust: rustfmt
Configure "format on save" in your editor settings. This single change saves hours.
Linter
- JavaScript/TypeScript: ESLint
- Python: Pylint or Flake8
- Ruby: RuboCop
Enable the --fix flag to auto-correct simple issues.
Editor Configuration
- Add
.editorconfigfile to ensure team consistency - Enable "Organize Imports on Save"
- Learn keyboard shortcuts: F2 (rename), Shift+Alt+F (format)
- Install language extensions for your IDE
Version Control Hooks
- Use Husky (JavaScript) or pre-commit (Python)
- Auto-format before every commit
- Run linter checks in CI/CD pipeline
With these tools configured, most refactoring becomes one-click operations.
💡 Making Refactoring a Habit
The difference between codebases that age gracefully and those that become unmaintainable isn't the initial quality—it's whether refactoring happens continuously or never.
Refactor when you're already there. Don't wait for a dedicated "cleanup sprint." Fix formatting issues as you encounter them. Rename variables when their purpose becomes clearer. Extract constants when you see magic numbers. Small improvements compound over time.
Set up auto-format on save. This eliminates 90% of formatting debates and manual work. In VS Code, add "editor.formatOnSave": true to your settings. In IntelliJ, enable "Reformat code" under Actions on Save. You'll never think about indentation again.
Learn keyboard shortcuts. Muscle memory makes refactoring effortless. Print a cheat sheet or practice these daily: F2 (rename), Shift+Alt+F (format), Ctrl+Shift+O (organize imports), Ctrl+D (select next occurrence). Speed comes from repetition.
Make small, atomic commits. One commit for "Rename variables," another for "Remove dead code." This makes code review easier, makes rollbacks simple if something breaks, and creates clear history showing your intent.
Test after each change. Even "safe" refactorings can surprise you. Run tests—or at least manually verify—after renaming public functions, moving files, reordering parameters, or deleting code you think is unused.
Trust version control. Never keep commented code "just in case." Git history preserves everything. Delete boldly, knowing you can retrieve it if needed. Clean code beats code archaeology.
📖 Glossary
Key terms used throughout this guide. Click any term to see its definition and how it applies to refactoring.