20 Prompts for Claude Code: From Refactoring to Architecture

20 Prompts for Claude Code: From Refactoring to Architecture

If you are a developer who spends more time reading legacy code than writing new features, you are not alone. A 2023 survey by the Software Engineering Institute found that developers spend up to 50% of their time understanding existing code before making changes. Claude Code, a terminal-based AI coding agent released by Anthropic in early 2025, has changed how many of us approach this problem. Instead of manually tracing through spaghetti logic, you can now delegate code comprehension, refactoring, and even architectural design to an AI that runs directly in your shell.

In this article, I share 20 prompts organized by skill level — basic, advanced, and expert. Each prompt includes a concrete task, the exact prompt text, and an example result. By the end, you will have a reusable toolkit for turning Claude Code into your senior developer pair.

Why Claude Code?

Claude Code is not a chatbot. It is an agent that reads your file system, executes commands, runs tests, and edits code. It operates on a context window of up to 200,000 tokens (as of July 2026), meaning it can analyze entire codebases in one go. According to Anthropic’s official documentation at docs.anthropic.com, Claude Code supports multi-file edits, git integration, and interactive debugging. Unlike previous AI coding tools that required copying and pasting code, Claude Code works directly in your terminal, making it ideal for refactoring and architecture tasks.

Basic Prompts: Code Comprehension and Local Refactoring

These prompts are for developers who are new to Claude Code or want to automate small, repetitive tasks.

1. Explain a Function

Task: Understand what a complex function does without reading every line.

Prompt:

Explain the function `calculateDiscount` in src/pricing.ts. Include:
1. Its input parameters and return type
2. The business logic step by step
3. Any edge cases it handles or misses

Example Result:

The function `calculateDiscount(orderTotal: number, customerTier: string, promoCode?: string): number` applies a discount to an order total. Logic:
1. If customerTier is 'gold', apply 20% discount.
2. If promoCode is 'SUMMER', apply additional 10%.
3. If orderTotal > 500, cap discount at 40%.
Edge cases: promoCode is undefined returns 0; negative orderTotal returns 0.
Missing: no handling for decimal precision.

2. Add Comments to a File

Task: Make a dense file readable for new team members.

Prompt:

Add JSDoc comments to all exported functions in src/utils/helpers.ts. Use TypeScript types and describe parameters, return values, and exceptions.

Example Result:

/**
 * Formats a date string to ISO 8601.
 * @param date - Date input as string or Date object.
 * @returns Formatted date string.
 * @throws {Error} If input is invalid.
 */
export function formatDate(date: string | Date): string {
  // ...
}

3. Rename a Variable Across Files

Task: Rename a poorly named variable everywhere it appears.

Prompt:

Rename the variable `x` to `userCount` in all files under src/controllers/. Use sed-like precision: only rename if it is a variable declaration or usage, not a substring in comments.

Example Result:
Claude Code modifies four files, replacing x with userCount in 12 locations. It does not touch x in strings or comments.

4. Extract a Function from a Block

Task: Improve readability by extracting a block of code into a named function.

Prompt:

In src/checkout.ts, lines 45-72 contain a block that validates credit card numbers. Extract it into a function `validateCreditCard(cardNumber: string): boolean`. Keep the original logic intact.

Example Result:

function validateCreditCard(cardNumber: string): boolean {
  const sanitized = cardNumber.replace(/\s/g, '');
  return /^\d{16}$/.test(sanitized) && luhnCheck(sanitized);
}

5. Convert Console.log to Structured Logging

Task: Replace ad-hoc logging with a proper logger.

Prompt:

Replace all `console.log` calls in src/services/ with `logger.info`. Import the logger from src/lib/logger.ts. If the console.log contains dynamic data, wrap it as an object: `logger.info({ message: '...', data: ... })`.

Example Result:
Before: console.log('User created:', user.id);
After: logger.info({ message: 'User created', userId: user.id });

Advanced Prompts: Multi-File Refactoring and Code Smells

These prompts require Claude Code to understand relationships between files and apply systematic improvements.

6. Remove Dead Code

Task: Eliminate unused exports and functions.

Prompt:

Scan all TypeScript files in src/. Find exported functions or classes that are never imported anywhere in the codebase (excluding test files). List them, then remove each one and its associated tests if they exist.

Example Result:
Claude Code identifies 5 dead functions, including legacyAuth() and unusedFormatter(). It deletes them from 3 files and removes 2 test files that only tested these functions.

7. Replace Callbacks with Async/Await

Task: Modernize callback-based code.

Prompt:

In src/data-access/, all functions use callbacks. Convert them to async/await. Return Promises explicitly. Update all call sites to use await instead of callback parameters.

Example Result:
Before:

function getUser(id: number, callback: (err: Error | null, user?: User) => void) {
  db.query('SELECT * FROM users WHERE id = ?', [id], (err, rows) => {
    if (err) return callback(err);
    callback(null, rows[0]);
  });
}

After:

async function getUser(id: number): Promise<User> {
  const rows = await db.query('SELECT * FROM users WHERE id = ?', [id]);
  return rows[0];
}

8. Extract Duplicated Logic into a Shared Module

Task: Reduce code duplication across services.

Prompt:

Find all occurrences of pagination logic in src/routes/. The pattern is: parse page and limit, validate, slice array. Extract this into a single function in src/lib/pagination.ts and update all routes to use it.

Example Result:
Claude Code creates pagination.ts with a paginate<T>(items: T[], page: number, limit: number): { data: T[], total: number } function. It updates 4 route files, removing 20 lines of duplicated code each.

9. Add Error Handling to All API Handlers

Task: Wrap unprotected route handlers with try-catch.

Prompt:

In src/routes/api/, every Express handler that uses async must have a try-catch block. If a handler lacks one, wrap the body in try-catch and call next(error) on failure. Use a consistent pattern.

Example Result:
Before:

app.get('/users', async (req, res) => {
  const users = await getUsers();
  res.json(users);
});

After:

app.get('/users', async (req, res, next) => {
  try {
    const users = await getUsers();
    res.json(users);
  } catch (error) {
    next(error);
  }
});

10. Sort Imports Consistently

Task: Enforce a consistent import order across the project.

Prompt:

Reorganize imports in all .ts files under src/ to follow this order: 1) Node built-ins, 2) third-party packages, 3) internal modules (src/), 4) relative imports. Within each group, sort alphabetically. Remove unused imports.

Example Result:
Claude Code processes 30 files, fixes 150 import statements, and removes 8 unused imports.

Expert Prompts: Architectural Design and Large-Scale Changes

These prompts require Claude Code to understand high-level patterns, suggest architectural improvements, and execute multi-step transformations.

11. Propose an Architecture for a New Feature

Task: Get a production-ready design for adding a new module.

Prompt:

We need to add a notification system to our Express app. Requirements:
- Support email, SMS, and push notifications
- Each channel has its own provider (e.g., SendGrid for email, Twilio for SMS)
- Notifications should be queued and retried on failure
- Use dependency injection for testability

Analyze the existing codebase in src/ (controllers, services, models). Suggest a folder structure, interfaces, and classes. Write the TypeScript code for the core abstractions: INotificationProvider, NotificationService, and a QueueManager. Do not implement providers yet, just interfaces.

Example Result:
Claude Code proposes:

src/
  notifications/
    interfaces/
      INotificationProvider.ts
      INotificationQueue.ts
    services/
      NotificationService.ts
      QueueManager.ts
    providers/
      email/
      sms/
      push/

It generates INotificationProvider with send(to: string, payload: object): Promise<SendResult> and NotificationService that iterates over registered providers.

12. Migrate from JavaScript to TypeScript

Task: Incrementally convert a JS file to TS with type definitions.

Prompt:

Convert src/models/old-model.js to TypeScript. Keep the file at src/models/old-model.ts. Add proper interfaces for all objects. Use JSDoc types as hints. Do not break imports from other files that still use .js.

Example Result:
Claude Code adds interface User { id: number; name: string; email: string; } and converts module.exports to export. It updates the export signature.

13. Introduce a Repository Pattern

Task: Abstract database access from business logic.

Prompt:

In src/services/userService.ts, all database queries are inline. Extract each query into a repository class `UserRepository` in src/repositories/. The repository should have methods like `findById`, `findAll`, `create`, `update`. Replace direct calls in the service with repository calls. Use dependency injection via constructor.

Example Result:
Claude Code creates UserRepository with 5 methods. It refactors userService.ts to accept UserRepository in the constructor, reducing coupling.

14. Implement a Feature Flag System

Task: Add runtime toggling for a new feature without branching.

Prompt:

Design and implement a simple feature flag system. Create a class `FeatureFlag` in src/lib/ that reads flags from a JSON config file. Use it to guard the new checkout flow in src/routes/checkout.ts. If flag 'new-checkout' is true, use new logic; otherwise, fall back to old.

Example Result:
Claude Code writes FeatureFlag with isEnabled(flagName: string): boolean and a flags.json file. It modifies checkout.ts to check the flag before routing.

15. Refactor a God Class

Task: Split a monolithic class into single-responsibility classes.

Prompt:

The class `OrderManager` in src/services/OrderManager.ts has 2000 lines and handles validation, pricing, inventory, shipping, and notifications. Apply the Single Responsibility Principle. Split it into: OrderValidator, PricingService, InventoryService, ShippingService, and NotificationService. Keep the public API of OrderManager as a facade that delegates to these new classes.

Example Result:
Claude Code creates 5 new files, moves methods, and rewrites OrderManager to compose them. The original file shrinks from 2000 to 200 lines.

Practical Workflow: Using Prompts in a Real Project

To get the most out of these prompts, follow this workflow:

  1. Start with claude in your terminal — ensure you have Claude Code installed and authenticated (requires Anthropic API key).
  2. Run claude with a prompt — you can pass prompts directly: claude "Explain the function calculateDiscount in src/pricing.ts".
  3. Review changes — Claude Code uses git diff to show changes before applying. Accept or reject per file.
  4. Iterate — if the result is not perfect, refine the prompt. For example, add "Only change files in src/, not tests".

Best Practices for Writing Prompts

Principle Example
Be specific about files and lines "In src/auth.ts, lines 10-30..."
Provide constraints "Do not modify test files"
Define output format "Return the code in TypeScript with JSDoc"
Use examples "Like this: // before -> // after"
Request explanations "Explain why you made each change"

Conclusion

Claude Code is not a magic wand — it is a tool that amplifies your own judgment. The 20 prompts in this article cover the spectrum from understanding a single function to redesigning an entire module. Start with the basic prompts to build confidence, then move to advanced and expert prompts as you learn to trust the agent. The key is clear, constrained, and context-rich instructions. With practice, you will reduce refactoring time from hours to minutes and free your mental energy for the architectural decisions that truly matter.

For teams looking to integrate AI-assisted development into their curriculum, structured courses can help. ASI Biont supports connecting to code repositories via API — for more information, visit asibiont.com/courses.

← All posts

Comments