Refactoring & Code Review with AI
Detect code smells, get naming improvements, and run AI-assisted PR reviews
Why AI Excels at Code Review
Code review is pattern recognition ā spotting anti-patterns, naming issues, and logic gaps. AI tools have seen millions of codebases and recognize these patterns instantly. The key is prompting effectively to get actionable suggestions, not generic advice.
AI misses: business context, team conventions, and product intent ā always apply human judgment.
Refactor Suggestions in Copilot Chat
Select a function, open Chat, and prompt with a specific goal:
// Select this function, then ask Copilot:
// "Refactor this to reduce nesting and improve readability"
function processOrder(order) {
if (order) {
if (order.items) {
if (order.items.length > 0) {
for (let item of order.items) {
if (item.inStock) {
ship(item);
}
}
}
}
}
}
// AI suggestion (early-return pattern):
function processOrder(order) {
if (!order?.items?.length) return;
const inStockItems = order.items.filter(item => item.inStock);
inStockItems.forEach(ship);
}Effective refactor prompts:
- "Reduce nesting using early returns"
- "Extract this into smaller functions, each doing one thing"
- "Replace this loop with functional equivalents (map/filter/reduce)"
- "Rename variables to be more descriptive"
Code Smell Detection
Ask AI to audit a file or class for common smells:
// Prompt: "Identify code smells in this class and explain each one"
class UserManager {
data = [];
// 200-line class doing auth, DB access, email, and logging
// AI will flag: God Object, SRP violation, mixed concerns
}
// Prompt: "List all places where this function violates DRY"
// Prompt: "Find magic numbers and suggest named constants"
// Prompt: "Identify any potential null pointer / undefined access issues"Naming Improvements
Poor naming is one of the most common review comments. AI is excellent at suggesting better names:
// Prompt: "Suggest better names for variables, params, and functions in this snippet"
// Before
function calc(d, r) {
const x = d * r;
const y = x * 0.08;
return x + y;
}
// AI suggestion
function calculateTotalWithTax(subtotal, quantity) {
const orderTotal = subtotal * quantity;
const taxAmount = orderTotal * TAX_RATE;
return orderTotal + taxAmount;
}AI-Assisted PR Reviews
Before submitting a PR, use AI to pre-review your own diff. This catches obvious issues before a human reviewer sees them.
git diff main..HEAD > pr-diff.txt
# Prompt: "Review this diff as if you're a senior engineer. Flag: logic bugs, missing edge cases, security issues, style violations, and anything that would get a 'request changes' comment."
Address AI-flagged issues, then re-run the review on the updated diff.
Security Scanning Prompts
AI can help spot common security vulnerabilities in your code:
// Prompts for security review: "Check this code for SQL injection vulnerabilities" "Identify any places where user input is not sanitized" "Flag any hardcoded secrets, API keys, or credentials" "Check for insecure direct object references (IDOR)" "Review this auth middleware for bypass vulnerabilities" // Example catch: const query = "SELECT * FROM users WHERE id = " + req.params.id; // AI flags: SQL injection ā use parameterized queries const query = "SELECT * FROM users WHERE id = ?"; db.query(query, [req.params.id]);
Performance Hints
Ask AI to identify expensive operations and suggest optimizations:
// Prompts:
"Find any O(n²) or worse complexity in this function"
"Identify database calls inside loops (N+1 problem)"
"Suggest where memoization would help"
"Are there any unnecessary re-renders in this React component?"
// Example N+1 catch:
for (const user of users) {
const orders = await db.query('SELECT * FROM orders WHERE user_id = ?', [user.id]);
// AI flags: N+1 query ā use a JOIN or batch load instead
}
// Suggested fix:
const orders = await db.query(
'SELECT * FROM orders WHERE user_id IN (?)',
[users.map(u => u.id)]
);Reviewing Diffs with Claude Code
Claude Code's context window handles entire files and diffs efficiently:
# In terminal, run Claude Code on a staged diff: git diff --staged | claude "Review this staged diff for any issues before I commit" # Or review a specific file's changes: claude "Review the changes in src/auth/middleware.ts and flag anything concerning" # Review with context: claude "Given that this is a financial transaction service, review auth.ts for security and correctness issues"
"Refactor this to reduce nesting using early returns"
"Identify code smells and categorize by severity"
"Suggest better names for all variables and functions here"
git diff main..HEAD, paste to AI, ask for senior engineer review
"Check for SQL injection, unsanitized input, hardcoded secrets"
"Identify database calls inside loops and suggest batch alternatives"
git diff --staged | claude "Review this before I commit"