- Learn
- Development Workflows
- Debugging and Code Review Workflows
Learn effective workflows for using AI in debugging sessions and code reviews—from finding bugs to ensuring quality.
Debugging and Code Review Workflows
AI excels at analyzing code, tracing execution paths, and spotting issues humans might miss. This lesson covers workflows for effective debugging and code review with AI assistance.
The AI Debugging Workflow
Phase 1: Gather Information
Before engaging AI, collect:
□ Exact error message and stack trace
□ Code where error occurs
□ Steps to reproduce
□ Environment details
□ Recent changes
□ What you've already tried
Phase 2: Structured Analysis
Present information systematically:
I need help debugging an issue.
## Error
TypeError: Cannot read properties of undefined (reading 'id') at processOrder (orders.ts:45) at handleCheckout (checkout.ts:23)
## Relevant Code
```typescript
// orders.ts:40-50
const processOrder = (order: Order) => {
const userId = order.user.id; // line 45
// ...
};
Reproduction
- Add item to cart
- Proceed to checkout
- Click "Place Order"
- Error appears in console
Environment
- Node.js 20.10, TypeScript 5.3
- Express 4.18, Prisma 5.7
- Windows 11
Recent Changes
- Updated user fetching to use React Query (yesterday)
- Changed Order type definition (2 days ago)
What I've Tried
- Added console.log(order) - shows order exists but user is undefined
- Checked database - user record exists
### Phase 3: Root Cause Analysis
Based on my debugging info above, help me:
- Identify the most likely root causes
- Explain why each could cause this error
- Suggest how to verify each cause
- Provide fixes for the most likely cause
### Phase 4: Fix and Verify
I believe the issue is [identified cause].
Suggest a fix that:
- Solves the immediate problem
- Prevents similar issues in the future
- Doesn't introduce new problems
Also suggest:
- How to verify the fix works
- What tests to add
## Rubber Duck Debugging
Use AI as an intelligent rubber duck:
I'm stuck debugging an issue and want to think through it out loud. Please ask me clarifying questions to help me find the bug.
The Problem: Users report that sometimes their cart is empty after page refresh, even though they just added items.
Let me walk through what I know:
- Cart is stored in localStorage
- We use React Context for cart state
- The issue happens intermittently
- More common on mobile devices
What questions should I consider?
**AI Response Style**:
- Asks probing questions
- Suggests areas to investigate
- Helps you think through the problem
## Systematic Code Review Workflow
### Pre-Review Setup
I'm reviewing code for [purpose].
Review Criteria:
- Correctness
- Security
- Performance
- Maintainability
- Error handling
- Test coverage
Context:
- This code handles [what it does]
- It's part of [larger system]
- Authors experience level: [junior/mid/senior]
- Risk level: [low/medium/high]
### Structured Review
Review this code using a systematic approach:
Code to review:
[paste code]
For each issue found, provide:
- Location: Line number or function
- Severity: Critical / High / Medium / Low
- Category: Security / Performance / Maintainability / Bug
- Description: What's the issue
- Suggestion: How to fix it
- Example: Code showing the fix
Also note:
- What's done well
- Overall assessment
### Security-Focused Review
Perform a security review of this code.
Code:
[code handling user input, auth, or sensitive data]
Specifically check for:
- Input validation and sanitization
- SQL/NoSQL injection vulnerabilities
- XSS (Cross-Site Scripting) risks
- Authentication/authorization flaws
- Sensitive data exposure
- CSRF vulnerabilities
- Insecure cryptography
- Path traversal
- Denial of service vectors
For each vulnerability:
- Describe the attack scenario
- Rate severity (CVSS-style if possible)
- Provide secure code fix
### Performance Review
Review this code for performance issues.
Code:
[code to review]
Context:
- Expected load: [requests/second or data size]
- Current performance: [if measured]
- Target performance: [goal]
Check for:
- Time complexity issues (O(n²) when O(n) possible)
- Memory leaks
- Unnecessary re-renders (React)
- N+1 query problems
- Missing memoization
- Blocking operations
- Large bundle size contributions
For each issue, estimate the impact and suggest optimization.
## Multi-File Review
When reviewing changes across multiple files:
Review this pull request spanning multiple files.
Summary of Changes
- Modified: auth.ts (added token refresh)
- Modified: api.ts (updated headers)
- Added: refreshToken.ts (new utility)
Files to Review
auth.ts (lines 45-80 changed)
[diff or changed code]
api.ts (lines 12-25 changed)
[diff or changed code]
refreshToken.ts (new file)
[full file]
Review for:
- Do the changes work together correctly?
- Are there integration issues?
- Is the approach consistent?
- Any shared state or race conditions?
## Code Review Checklists
### General Review Checklist
□ Code compiles/builds without errors □ All tests pass □ New tests added for new functionality □ No console.log or debug code left □ Error handling is appropriate □ Edge cases are handled □ Naming is clear and consistent □ Comments explain "why", not "what" □ No code duplication □ Changes match the PR description
### React-Specific Checklist
□ useEffect has correct dependency arrays □ No missing cleanup functions □ State updates don't cause infinite loops □ Memoization used where beneficial □ Keys are stable and unique in lists □ Accessibility attributes present □ Event handlers don't create new functions unnecessarily □ Props have appropriate types
### API-Specific Checklist
□ Input validation on all endpoints □ Appropriate HTTP status codes □ Error responses don't leak sensitive info □ Authentication required where needed □ Rate limiting considered □ Request/response properly typed □ Database transactions where needed □ Proper error handling and logging
## Post-Mortem Analysis
After fixing a bug, do a retrospective:
Help me write a post-mortem for this bug.
Bug Summary
[description of what happened]
Impact
- Users affected: [number]
- Duration: [time]
- Severity: [level]
Root Cause
[what caused it]
Fix
[how it was fixed]
Questions for Post-Mortem
- How could we have prevented this?
- How could we have detected it sooner?
- What process improvements should we make?
- What technical safeguards should we add?
- What should we monitor going forward?
## Debugging Different Bug Types
### State Management Bugs
Debug this React state issue.
Symptom: [what's happening] Expected: [what should happen]
State-related code:
[useState, useReducer, context code]
Component hierarchy: [list components and data flow]
When does it fail: [specific user actions]
### Async/Race Condition Bugs
I suspect a race condition.
Symptom: [intermittent behavior]
Async code involved:
[async functions, promises, event handlers]
Questions:
- What operations are happening concurrently?
- What shared state are they accessing?
- What's the expected order of operations?
- What order is actually happening?
### Memory Leaks
Debug this potential memory leak.
Symptoms:
- Memory grows over time
- App becomes slower after extended use
- [other symptoms]
Suspected code:
[subscriptions, event listeners, timers]
Using Chrome DevTools, I see: [heap snapshot findings]
What's causing the leak and how do I fix it?
## Review Feedback Tone
When AI helps write review comments:
Rewrite these review findings with a constructive tone. The developer is junior, so be educational, not critical.
Findings:
- [technical issue 1]
- [technical issue 2]
Format as PR comments that:
- Start with what's done well (if applicable)
- Explain the issue clearly
- Explain why it matters
- Provide a solution or direction
- Offer to discuss if needed
## Practice Exercise
Practice with a multi-stage debugging scenario:
1. **Given this bug report**: "Users sometimes see old data after editing"
2. **Generate** the debugging questions you'd ask
3. **Analyze** mock stack trace and code
4. **Identify** potential root causes
5. **Propose** fixes with verification steps
6. **Write** tests to prevent regression
## Summary
- Gather complete information before asking AI for help
- Use structured formats for debugging requests
- Apply systematic checklists for code review
- Match review depth to code risk level
- Do post-mortems to prevent future bugs
- Use constructive tone in review feedback
## Next Steps
Let's explore Git workflows with AI—how to write better commits, PRs, and manage version control effectively.