15 Prompts for Claude Code: From Refactoring to Architecture

You are a hands-on developer who uses AI daily to speed up work. This collection of prompts for Claude Code is battle-tested and covers the most common tasks: code review, refactoring, and architecture design. Each prompt comes with a real usage example in Python or TypeScript. No fluff – just working templates you can copy and adapt.

How to Use These Prompts

All prompts are designed to be used with Claude Code (Anthropic's CLI tool). Simply append the prompt to your file context or paste it into a conversation. Adjust language and framework details as needed.

1. Code Review: Style and Best Practices

Prompt:

Review the following code for style violations, security issues, and performance problems. Suggest fixes following [PEP 8 / language style guide] and document each issue with a severity label (high/medium/low).

Example usage:

// Paste this alongside a Python function:
def fetch_data(url, timeout=5):
    import requests
    r = requests.get(url, timeout=timeout)
    return r.json()

Claude's output:
- Medium: import statement should be at top of file.
- Low: Missing docstring.
- Low: r.json() may raise ValueError – no exception handling.

2. Code Review: Diff Analysis

Prompt:

Here is a diff of changes. Identify any regressions, test coverage gaps, and whether the change follows the principle of least surprise.

Example:

diff --git a/app.py b/app.py
@@ -10,7 +10,7 @@ def process(items):
     results = []
     for item in items:
-        if item.status == 'active':
+        if item.status != 'inactive':
             results.append(item)
     return results

Claude will explain that the logic now includes items with None status, potentially causing bugs.

3. Refactoring: Extract Method

Prompt:

Extract the logic inside the following function into a separate, well-named method. Apply the Single Responsibility Principle.

Example (TypeScript):

function sendOrderConfirmation(user: User, order: Order) {
    const emailBody = `Dear ${user.name}, your order #${order.id} is confirmed.`;
    const email = new Email(user.email, "Order Confirmation", emailBody);
    email.send();
    log(`Order confirmation sent to ${user.email}`);
}

Claude extracts:

function buildConfirmationEmail(user: User, order: Order): string { ... }
function logEmailSent(email: string): void { ... }
function sendOrderConfirmation(user: User, order: Order) {
    const emailBody = buildConfirmationEmail(user, order);
    const email = new Email(user.email, "Order Confirmation", emailBody);
    email.send();
    logEmailSent(user.email);
}

4. Refactoring: Replace Conditional with Polymorphism

Prompt:

Refactor this switch/if-else chain using polymorphism. Create a base class and concrete implementations for each case.

Example (Python):

def get_discount(customer_type):
    if customer_type == "regular":
        return 0.05
    elif customer_type == "premium":
        return 0.1
    elif customer_type == "vip":
        return 0.2
    else:
        return 0

Claude produces a Customer base class with get_discount() method overridden by RegularCustomer, PremiumCustomer, VIPCustomer. Eliminates the chain.

5. Refactoring: Simplify Complex Conditionals

Prompt:

Simplify the following conditional expression. Extract meaningful boolean variables or use guard clauses.

Example (JavaScript):

if (user && user.isActive && !user.isBlocked && (user.role === 'admin' || user.role === 'moderator')) { ... }

Claude suggests:

const isValidAdmin = user && user.isActive && !user.isBlocked && ['admin','moderator'].includes(user.role);
if (isValidAdmin) { ... }

6. Architecture: Domain Model Design

Prompt:

Design a domain model for [e-commerce / social network / inventory system]. List core entities, their attributes, relationships, and bounded contexts. Use Ubiquitous Language.

Example for a task management app:

Entities: Task, Project, User, Comment
Relationships: Project has many Tasks, User creates Tasks, Task has many Comments.
Bounded Context: Task Management, User Management, Notification.

7. Architecture: Hexagonal Architecture (Ports & Adapters)

Prompt:

Given the following business logic, structure it using Hexagonal Architecture. Identify ports (interfaces) and adapters (implementations for database, external API, console).

Example (Python):

# Core domain
class OrderService:
    def __init__(self, repo: OrderRepository):
        self.repo = repo
# Port (interface)
class OrderRepository(ABC):
    @abstractmethod
    def save(self, order): ...
# Adapter
class PostgresOrderRepository(OrderRepository):
    def save(self, order): ...

Claude will output the full skeleton with dependency injection and inversion.

8. Architecture: Event-Driven Design

Prompt:

Design an event-driven architecture for a system that sends notifications after an order is placed. Define events, event bus, handlers, and possible failure scenarios.

Example output:

Event: OrderPlaced (orderId, userId, timestamp)
Bus: in-memory event bus
Handlers: EmailHandler, SMSHandler, AnalyticsHandler
Failure: retry with backoff, dead letter queue

9. Code Quality: Add Type Hints

Prompt:

Add type hints to the following Python code. Use Optional, List, Dict where appropriate. Follow PEP 484.

Example:

def get_user(name):
    users = {'Alice': 30}
    return users.get(name)

Claude adds:

from typing import Optional
def get_user(name: str) -> Optional[int]: ...

10. Dependency Analysis

Prompt:

Analyze the import dependencies in this module. Detect circular dependencies and suggest how to break them using dependency inversion or a mediator pattern.

Example file:

# module_a.py
from module_b import B
class A: ...

Claude will generate a dependency graph and propose splitting into interfaces.

11. Unit Test Generation

Prompt:

Generate unit tests for the following class using pytest. Cover happy path, edge cases, and invalid inputs. Use fixtures and mocks where necessary.

Example:

class Calculator:
    def divide(self, a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b

Claude outputs test functions: test_divide_positive, test_divide_by_zero, test_divide_negative, etc.

12. Refactoring: Remove Dead Code

Prompt:

Identify and remove dead code (unused functions, classes, imports) from the following module. Document each removal.

Example:

import math
def old_calc(x):
    return x * 2
def new_calc(x):
    return x * 3

Claude removes old_calc and unused imports.

13. Performance: Database Query Optimization

Prompt:

Review the following SQL query and suggest indexing strategies, query rewrite, or pagination improvements.

Example:

SELECT * FROM orders WHERE user_id = 123 ORDER BY created_at DESC;

Claude suggests adding composite index on (user_id, created_at) and using LIMIT with offset or keyset pagination.

14. Architecture: API Design (RESTful)

Prompt:

Design a RESTful API for a blog platform. List endpoints, HTTP methods, request/response shapes, status codes, and authentication scheme.

Claude outputs endpoints like GET /posts, POST /posts, with JWT bearer auth.

15. Secure Coding: Input Validation

Prompt:

Add input validation and sanitization to the following function. Use allowlisting where possible. Guard against injection attacks (SQL, command, XSS).

Example (Node.js):

app.get('/user/:id', (req, res) => {
    db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);
});

Claude rewrites with parameterized query and numeric validation.

16. Migration: Legacy to Modern Code

Prompt:

This legacy code uses callbacks. Rewrite it using async/await and modern error handling (try/catch). Keep the same behaviour.

Example (JavaScript callback):

function getUser(id, callback) {
    db.query('SELECT ...', (err, rows) => {
        if (err) return callback(err);
        callback(null, rows[0]);
    });
}

Claude produces an async getUser(id) with try/catch.

17. Architecture: Microservice Decomposition

Prompt:

Given a monolith's modules, propose a microservice decomposition. Define service boundaries based on bounded contexts, data ownership, and communication patterns (sync vs async).

Claude will output a diagram-like description with services: User Service, Order Service, Inventory Service.

Conclusion

These prompts are meant to be starting points. Adapt them to your language, framework, and coding standards. The best results come when you provide enough context – include relevant code and describe your constraints. Use Claude Code iteratively: first get a rough suggestion, then refine with follow-up prompts. Over time you'll build a personal library of prompts that match your workflow.

Try one of these prompts with your next pull request or design session. You'll likely find you save hours each week.

← All posts

Comments