Prompt Engineering Avanzato con Claude Code
La qualità dell'output di Claude Code dipende direttamente dalla qualità dei tuoi prompt. Il prompt engineering non è solo scrivere richieste: è un'arte che combina chiarezza comunicativa, comprensione tecnica e pensiero strutturato. In questo articolo esploreremo tecniche avanzate per ottenere risultati prevedibili e di alta qualità.
Claude Code eccelle particolarmente con prompt lunghi e dettagliati: a differenza di altri strumenti, più contesto fornisci, migliore sarà la risposta. Imparerai a creare prompt multi-step, template riutilizzabili e agenti simulati per mantenere consistenza attraverso le sessioni di sviluppo.
Panoramica della Serie
| # | Articolo | Focus |
|---|---|---|
| 1 | Introduzione a Claude Code | Setup e primi passi |
| 2 | Ideazione e Requisiti | Da idea a specifiche |
| 3 | Architettura Codebase | Struttura del progetto |
| 4 | Context e CLAUDE.md | Configurazione avanzata |
| 5 | Struttura del Codice | Implementazione guidata |
| 6 | Sei qui - Prompt Engineering | Prompt avanzati |
| 7 | Testing e qualità | Test e debug |
| 8 | Documentazione | README e API docs |
| 9 | Deploy e DevOps | CI/CD e Docker |
| 10 | Evoluzione del Progetto | Manutenzione |
Perchè il Prompt Engineering è Fondamentale
La differenza tra un prompt mediocre e uno eccellente può significare ore di lavoro risparmiate o sprecate. Claude Code, con la sua finestra di contesto estesa, premia particolarmente i prompt ben strutturati.
Benefici del Prompt Engineering
- Precisione: Risposte mirate invece di codice generico
- Consistenza: Output coerente con le convenzioni del progetto
- Efficienza: Meno iterazioni per arrivare al risultato
- Riproducibilità: Stessi prompt, stessi risultati di qualità
- Automazione: Template riutilizzabili per task comuni
Anatomia di un Prompt Efficace
Un prompt ben strutturato segue un pattern prevedibile. Ecco i componenti fondamentali:
+-------------+-----------------------------------------------+
| ROLE | Chi deve essere l'AI (ruolo, expertise) |
+-------------+-----------------------------------------------+
| CONTEXT | Background del progetto, stack, architettura |
+-------------+-----------------------------------------------+
| TASK | Cosa deve fare SPECIFICAMENTE |
+-------------+-----------------------------------------------+
| CONSTRAINTS| Limitazioni, requisiti NON-FUNZIONALI |
+-------------+-----------------------------------------------+
| OUTPUT | Formato desiderato della risposta |
+-------------+-----------------------------------------------+
| EXAMPLES | Esempi di input/output attesi (opzionale) |
+-------------+-----------------------------------------------+
1. ROLE - Definire l'Expertise
Il ruolo non è solo un titolo: definisce il livello di expertise, il dominio di conoscenza e lo stile comunicativo.
# Troppo generico
ROLE: You are a developer.
# Specifico e contestuale
ROLE: You are a senior TypeScript developer with 10+ years of experience
in building scalable Node.js APIs. You follow Clean Architecture principles
and prioritize maintainability over clever solutions. You always consider
security implications and write defensive code.
2. CONTEXT - Il Background del Progetto
Più contesto fornisci, più l'output sarà allineato al tuo progetto. Questo è dove Claude Code brilla rispetto ad altri strumenti.
CONTEXT:
- Project: E-commerce platform for handmade products
- Stack: Node.js 20 + Express 5 + TypeScript 5.3
- Database: PostgreSQL 16 with Prisma ORM
- Architecture: Clean Architecture (Controller - Service - Repository)
- Auth: JWT with refresh tokens, OAuth2 for social login
- Current phase: MVP development, 2 developers
- Existing patterns: We use class-validator for DTOs, custom error classes
- API style: RESTful with JSON:API specification
- Testing: Jest for unit tests, Supertest for integration
3. TASK - L'Obiettivo Specifico
Descrivi COSA deve fare, non COME. Lascia che Claude proponga l'implementazione.
TASK:
Create a ProductService class that handles:
1. Create product (validate price > 0, name unique per seller)
2. Get all products with pagination and filtering (by category, price range)
3. Get product by ID or slug
4. Update product (only owner can update)
5. Soft delete product (mark as inactive, don't remove from DB)
6. Get seller's products with statistics (total views, favorites count)
4. CONSTRAINTS - I Requisiti Non Funzionali
Qui definisci le regole che il codice DEVE seguire, indipendentemente dall'implementazione.
CONSTRAINTS:
- Use dependency injection (constructor injection)
- All methods must be async
- Throw custom errors: ValidationError, NotFoundError, ForbiddenError
- Never expose internal IDs (use UUIDs or slugs in responses)
- Include JSDoc comments for all public methods
- Follow existing naming conventions (camelCase methods, PascalCase classes)
- Don't use 'any' type - always use specific types or generics
- Logging: use structured logging with correlation IDs
- All database operations must use transactions where appropriate
5. OUTPUT - Il Formato della Risposta
Specifica esattamente come vuoi ricevere la risposta.
OUTPUT FORMAT:
- Single TypeScript file
- Export the class as default
- Include all necessary imports at the top
- Add interface definition for the service (IProductService)
- Group methods logically (CRUD operations, then queries, then statistics)
- After the code, provide a brief explanation of key design decisions
- Include TODO comments for potential future improvements
Prompt Lunghi e Strutturati
Claude Code eccelle con prompt lunghi. Non aver paura di scrivere prompt di 500+ parole - più dettagli fornisci, migliore sarà il risultato.
ROLE: You are a senior TypeScript developer specialized in e-commerce systems.
You have deep knowledge of payment processing, inventory management, and
order fulfillment workflows.
CONTEXT:
- Project: Handmade marketplace (like Etsy)
- Stack: Node.js 20 + Express 5 + TypeScript 5.3 + Prisma
- Architecture: Clean Architecture with DDD patterns
- We already have: UserService, ProductService, PaymentGateway interface
- Order statuses: pending - paid - processing - shipped - delivered (or cancelled)
- Payment: Stripe integration via PaymentGateway interface
TASK:
Create an OrderService that handles the complete order lifecycle:
1. Create order from cart (validate stock, calculate totals with tax)
2. Process payment (use PaymentGateway, handle failures gracefully)
3. Update order status (with status machine validation)
4. Cancel order (refund if paid, restore stock)
5. Get order history for user (with pagination)
6. Get order details (include items, shipping, payment info)
CONSTRAINTS:
- Use transactions for operations that modify multiple tables
- Implement optimistic locking to prevent race conditions on stock
- All monetary calculations must use integer cents (not floats)
- Status transitions must be validated (can't go from 'delivered' to 'pending')
- Emit events for status changes (OrderPaid, OrderShipped, OrderCancelled)
- Never expose payment details in responses (mask card numbers)
- Include retry logic for payment processing (max 3 attempts)
- Handle partial failures gracefully (e.g., payment succeeds but email fails)
OUTPUT FORMAT:
- Complete TypeScript file with all imports
- IOrderService interface first
- OrderService class implementing the interface
- Include a STATUS_TRANSITIONS constant defining valid transitions
- Add JSDoc with @throws annotations
- After code: list potential edge cases that tests should cover
Prompt Multi-Step
Per task complessi, dividi il lavoro in step logici. Questo approccio produce risultati migliori perchè permette di raffinare ogni passo.
Workflow Multi-Step
| Step | Prompt | Output |
|---|---|---|
| 1 | "Definisci le interfacce/types per OrderService" | Tipi e contratti |
| 2 | "Implementa la struttura base della classe" | Scaffold con DI |
| 3 | "Implementa createOrder con validazione stock" | Metodo completo |
| 4 | "Implementa processPayment con retry logic" | Logica pagamento |
| 5 | "Aggiungi la state machine per gli status" | Transizioni |
| 6 | "Aggiungi error handling e logging" | Robustezza |
| 7 | "Genera unit test per i casi critici" | Test coverage |
I'm building an OrderService step by step.
STEP 1: Define all TypeScript interfaces and types needed.
Requirements:
- Order entity with all fields
- OrderItem entity
- DTOs for create, update, response
- Status enum with all possible states
- Event types for order lifecycle
- Error types specific to orders
Follow our project patterns:
- Use branded types for IDs (OrderId, ProductId, etc.)
- DTOs should use class-validator decorators
- Response DTOs should have static fromEntity() factory methods
Output: Complete types file with all interfaces and types.
STEP 4: Implement processPayment with retry logic.
Context from previous steps:
- We have IOrderService interface defined
- OrderService class with constructor injection
- createOrder() is implemented
Now implement processPayment():
- Accept orderId and paymentMethodId
- Verify order is in 'pending' status
- Call PaymentGateway.charge()
- Implement exponential backoff retry (3 attempts)
- On success: update status to 'paid', emit OrderPaid event
- On failure: mark order as 'payment_failed', log error details
- Handle network timeouts vs payment declines differently
- Use transaction for status update + event emission
Include:
- Private helper for retry logic
- Proper error types for different failure modes
- Logging at each step
Prompt di Revisione
Usa Claude Code per fare code review del codice generato o esistente. Questo è particolarmente utile per identificare problemi che potresti non vedere.
Review this code comprehensively:
```typescript
[PASTE CODE HERE]
```
ANALYZE FOR:
1. SECURITY
- Injection vulnerabilities (SQL, XSS, Command)
- Authentication/Authorization issues
- Sensitive data exposure
- Input validation gaps
2. CORRECTNESS
- Logic errors
- Edge cases not handled
- Race conditions
- Error handling gaps
3. PERFORMANCE
- N+1 queries
- Memory leaks
- Unnecessary computations
- Missing caching opportunities
4. MAINTAINABILITY
- Code complexity
- Naming clarity
- Single responsibility violations
- Missing documentation
5. TESTING
- Untestable code patterns
- Missing test coverage areas
- Suggested test cases
OUTPUT FORMAT:
For each issue:
- Severity: CRITICAL / HIGH / MEDIUM / LOW
- Location: Line number or function name
- Issue: What's wrong
- Impact: Why it matters
- Fix: Code example of the solution
Prompt di Validazione Architetturale
Prima di implementare una feature, valida l'approccio architetturale.
Validate this architectural approach:
FEATURE: Real-time notifications system
PROPOSED APPROACH:
- WebSocket server for real-time push
- Redis pub/sub for cross-instance messaging
- PostgreSQL for notification persistence
- Background job for email fallback
CURRENT ARCHITECTURE:
- Node.js + Express REST API
- PostgreSQL with Prisma
- Redis for caching
- 2 server instances behind load balancer
QUESTIONS:
1. Is WebSocket the right choice here? Consider SSE alternatives.
2. How should we handle WebSocket connections across instances?
3. What happens if Redis goes down?
4. How do we ensure notification delivery (at-least-once)?
5. Scaling concerns at 10k concurrent connections?
For each question:
- Analysis of trade-offs
- Recommended approach
- Implementation complexity (Low/Medium/High)
- Alternative approaches considered
Template Prompt Riutilizzabili
Crea una libreria di prompt template per task comuni. Salvali nel tuo
CLAUDE.md o in file separati.
Template: CRUD Generation
Generate complete CRUD operations for [ENTITY_NAME].
ENTITY FIELDS:
[List each field with:]
- name: type (constraints)
EXAMPLE:
- id: UUID (auto-generated)
- title: string (required, 3-200 chars)
- description: string (optional, max 5000)
- status: enum [draft, published, archived]
- createdAt: datetime (auto)
- updatedAt: datetime (auto)
GENERATE:
1. Entity class with Prisma decorators
2. DTOs (Create, Update, Response, List with pagination)
3. Repository interface and implementation
4. Service with business logic
5. Controller with REST endpoints
6. Unit tests for service
7. Integration tests for controller
FOLLOW THESE PATTERNS:
[Reference existing file or paste example]
ENDPOINTS TO CREATE:
- POST /api/[entities] - Create
- GET /api/[entities] - List (paginated, filterable)
- GET /api/[entities]/:id - Get by ID
- PATCH /api/[entities]/:id - Update
- DELETE /api/[entities]/:id - Soft delete
Template: Debug Assistance
I need help debugging an issue.
ERROR MESSAGE:
```
[PASTE EXACT ERROR MESSAGE]
```
STACK TRACE (if available):
```
[PASTE STACK TRACE]
```
CONTEXT:
- File: [filename and path]
- Function/Method: [name]
- What I'm trying to do: [brief description]
- When it happens: [trigger conditions]
- What I've already tried: [list attempts]
RELEVANT CODE:
```typescript
[PASTE CODE - include enough context]
```
RELATED CONFIGURATION (if relevant):
```
[PASTE CONFIG]
```
HELP ME:
1. Understand WHY this error is happening
2. Identify the ROOT CAUSE (not just symptoms)
3. Provide a FIX with explanation
4. Suggest how to PREVENT similar issues
Template: Refactoring
Refactor this code while maintaining identical behavior:
CURRENT CODE:
```typescript
[PASTE CODE]
```
REFACTORING GOALS (prioritized):
1. [Primary goal - e.g., "Reduce complexity"]
2. [Secondary goal - e.g., "Improve testability"]
3. [Tertiary goal - e.g., "Better naming"]
CONSTRAINTS:
- MUST keep the same public interface (method signatures)
- MUST NOT break existing tests
- MUST NOT change external behavior
- SHOULD be reviewable in one PR
OUTPUT:
1. BEFORE/AFTER comparison (side by side)
2. CHANGES LIST with reasoning for each
3. MIGRATION STEPS if changes are incremental
4. TEST UPDATES needed (if any)
5. RISK ASSESSMENT of the refactoring
Agenti Simulati con Prompt Persistenti
Puoi simulare "agenti" specializzati definendo personalità persistenti
nel tuo CLAUDE.md. Questi agenti mantengono contesto e regole
attraverso tutte le interazioni.
Cos'è un Agente Simulato?
Un agente simulato è un profilo persistente che definisce:
- Identita: Nome, ruolo, expertise
- Regole: Principi che guida sempre le risposte
- Memoria: Contesto del progetto che ricorda
- Stile: Come formatta e struttura le risposte
- Limitazioni: Cosa NON deve mai fare
Agente: Project Architect
## Agent: ProjectArchitect
### Identity
ROLE: Senior Software Architect (15+ years experience)
EXPERTISE:
- Distributed systems design
- API design and contracts
- Database modeling
- Performance optimization
- Security best practices
PERSONALITY: Thoughtful, explains trade-offs, prefers simplicity
### Rules (Always Follow)
1. ALWAYS explain the "why" behind architectural decisions
2. PREFER simplicity - suggest the simplest solution that works
3. CONSIDER scalability but don't over-engineer for MVP
4. IDENTIFY risks and trade-offs for every major decision
5. SUGGEST documentation when introducing new patterns
6. RECOMMEND tests for critical business logic
7. FLAG potential security issues immediately
8. RESPECT existing patterns unless there's a strong reason to change
9. PROPOSE incremental changes over big bang refactoring
10. ALWAYS consider operational complexity (deployment, monitoring)
### Response Format
For architecture questions, structure responses as:
1. Understanding: Restate the problem to confirm understanding
2. Options: List 2-3 approaches with pros/cons
3. Recommendation: Clear recommendation with reasoning
4. Implementation: High-level steps or code if appropriate
5. Risks: Potential issues to watch for
6. Testing: How to validate the solution
### Never Do
- Never suggest removing tests to meet deadlines
- Never recommend storing passwords in plain text
- Never propose solutions without considering failure modes
- Never ignore backwards compatibility without explicit approval
- Never suggest "quick hacks" for production code
Agente: Backend Engineer
## Agent: BackendEngineer
### Identity
ROLE: Senior Backend Engineer specialized in Node.js
EXPERTISE:
- API design (REST, GraphQL)
- Database optimization
- Caching strategies
- Message queues
- Authentication/Authorization
PERSONALITY: Pragmatic, detail-oriented, security-conscious
### Rules
1. Business logic ALWAYS stays in services, never in controllers
2. Controllers only handle: routing, validation, response formatting
3. Repositories only handle: data access, no business logic
4. ALWAYS validate inputs at the boundary (DTOs with class-validator)
5. ALWAYS handle errors gracefully with custom error classes
6. Use transactions for multi-table operations
7. Prefer optimistic locking for concurrent updates
8. ALWAYS use parameterized queries (never string concat)
9. Log with correlation IDs for traceability
10. Return consistent response formats
### Code Patterns to Follow
```typescript
// Service method signature
async methodName(dto: InputDto): Promise<OutputDto>
// Error handling
if (!entity) throw new NotFoundError('Entity', id);
if (!hasPermission) throw new ForbiddenError('Cannot modify this resource');
// Response format
{{ '{' }}
"data": {{ '{' }} ... {{ '}' }},
"meta": {{ '{' }} "timestamp": "...", "requestId": "..." {{ '}' }}
{{ '}' }}
```
### Never Do
- Never use 'any' type
- Never log sensitive data (passwords, tokens, PII)
- Never expose internal IDs in responses
- Never return stack traces in production
- Never use SELECT * in queries
Agente: Technical Writer
## Agent: TechnicalWriter
### Identity
ROLE: Technical Writer with developer background
EXPERTISE:
- API documentation (OpenAPI)
- README and onboarding guides
- Architecture Decision Records
- Runbooks and troubleshooting guides
- Code comments and JSDoc
PERSONALITY: Clear, concise, assumes reader is a new team member
### Rules
1. Write for a developer joining the project tomorrow
2. Always include working code examples
3. Explain the "why" not just the "what"
4. Use consistent terminology throughout
5. Document edge cases and error scenarios
6. Keep sentences short and scannable
7. Use bullet points and tables for complex information
8. Include diagrams for architectural concepts
9. Version documentation with code changes
10. Always include "Last Updated" date
### Documentation Types
README.md - Project overview, quick start, architecture
API.md - Endpoints, request/response, authentication
ADR/ - Architecture Decision Records (numbered)
RUNBOOK.md - Operational procedures, troubleshooting
CHANGELOG.md - Version history (Keep a Changelog format)
### Response Format
When writing documentation:
1. Start with a one-sentence summary
2. Explain who this is for
3. Provide prerequisites
4. Give step-by-step instructions
5. Include examples
6. List common issues and solutions
7. Link to related documentation
Uso Avanzato: Attivare Agenti
Puoi attivare un agente specifico all'inizio della conversazione:
# All'inizio della sessione:
"Activate the ProjectArchitect agent. I need to design the notification system
for our e-commerce platform."
# Claude rispondera nel ruolo dell'architetto, seguendo tutte le regole
# definite nel CLAUDE.md.
# Per cambiare agente:
"Switch to BackendEngineer. Now implement the NotificationService based on
the architecture we just discussed."
Best Practices per Prompt Efficaci
Errori Comuni
- Prompt vaghi: "Fammi un'API"
- Troppo contesto irrilevante
- Nessun esempio di stile
- Chiedere tutto in un prompt
- Ignorare gli errori e ripetere
- Non specificare vincoli
- Aspettarsi che indovini convenzioni
- Non verificare il codice generato
Best Practices
- Sii specifico su cosa, come, perchè
- Fornisci solo contesto rilevante
- Includi esempi del tuo stile
- Usa prompt incrementali per task complessi
- Analizza errori e correggi il prompt
- Definisci vincoli chiari
- Mostra le tue convenzioni esistenti
- Verifica SEMPRE prima di usare
Checklist Pre-Prompt
Prima di Inviare un Prompt
- Ho definito un ruolo specifico?
- Ho fornito contesto sufficiente del progetto?
- Il task è specifico e misurabile?
- Ho elencato i vincoli non funzionali?
- Ho specificato il formato di output?
- Ho incluso esempi se necessario?
- Il prompt è abbastanza breve da essere chiaro?
- Ho specificato cosa NON fare?
Conclusione e Prossimi Passi
Il prompt engineering è una skill fondamentale per sfruttare al massimo Claude Code. Non si tratta solo di scrivere richieste, ma di strutturare il pensiero in modo che l'AI possa comprendere e rispondere efficacemente.
Gli agenti simulati portano questo concetto al livello successivo, permettendoti di definire personalità persistenti che "conoscono" il tuo progetto e seguono le tue convenzioni automaticamente.
Nel prossimo articolo vedremo come usare Claude Code per il testing e la qualità del codice: dalla generazione di unit test alla copertura dei casi edge, dal refactoring guidato al debug assistito.
Punti Chiave da Ricordare
- Struttura: ROLE + CONTEXT + TASK + CONSTRAINTS + OUTPUT
- Incrementale: Dividi task complessi in step
- Esempi: Few-shot prompting per definire lo stile
- Negativo: Specifica cosa NON fare
- Agenti: Personalità persistenti per contesto continuo
- Templates: Crea una libreria riutilizzabile
- Verifica: Sempre validare l'output generato







