Intermediate20 min

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:

Terminal
 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:

Terminal
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)

Terminal

## Relevant Code
```typescript
// orders.ts:40-50
const processOrder = (order: Order) => {
  const userId = order.user.id;  // line 45
  // ...
};

Reproduction

  1. Add item to cart
  2. Proceed to checkout
  3. Click "Place Order"
  4. 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
Terminal

### Phase 3: Root Cause Analysis

Based on my debugging info above, help me:

  1. Identify the most likely root causes
  2. Explain why each could cause this error
  3. Suggest how to verify each cause
  4. Provide fixes for the most likely cause
Terminal

### Phase 4: Fix and Verify

I believe the issue is [identified cause].

Suggest a fix that:

  1. Solves the immediate problem
  2. Prevents similar issues in the future
  3. Doesn't introduce new problems

Also suggest:

  • How to verify the fix works
  • What tests to add
Terminal

## 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?

Terminal

**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]
Terminal

### Structured Review

Review this code using a systematic approach:

Code to review:

Terminal
[paste code]

For each issue found, provide:

  1. Location: Line number or function
  2. Severity: Critical / High / Medium / Low
  3. Category: Security / Performance / Maintainability / Bug
  4. Description: What's the issue
  5. Suggestion: How to fix it
  6. Example: Code showing the fix

Also note:

  • What's done well
  • Overall assessment
Terminal

### Security-Focused Review

Perform a security review of this code.

Code:

Terminal
[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:

  1. Describe the attack scenario
  2. Rate severity (CVSS-style if possible)
  3. Provide secure code fix
Terminal

### Performance Review

Review this code for performance issues.

Code:

Terminal
[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.

Terminal

## 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)

Terminal
[diff or changed code]

api.ts (lines 12-25 changed)

Terminal
[diff or changed code]

refreshToken.ts (new file)

Terminal
[full file]

Review for:

  1. Do the changes work together correctly?
  2. Are there integration issues?
  3. Is the approach consistent?
  4. Any shared state or race conditions?
Terminal

## 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

Terminal

### 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

Terminal

### 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

Terminal

## 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

  1. How could we have prevented this?
  2. How could we have detected it sooner?
  3. What process improvements should we make?
  4. What technical safeguards should we add?
  5. What should we monitor going forward?
Terminal

## Debugging Different Bug Types

### State Management Bugs

Debug this React state issue.

Symptom: [what's happening] Expected: [what should happen]

State-related code:

Terminal
[useState, useReducer, context code]

Component hierarchy: [list components and data flow]

When does it fail: [specific user actions]

Terminal

### Async/Race Condition Bugs

I suspect a race condition.

Symptom: [intermittent behavior]

Async code involved:

Terminal
[async functions, promises, event handlers]

Questions:

  1. What operations are happening concurrently?
  2. What shared state are they accessing?
  3. What's the expected order of operations?
  4. What order is actually happening?
Terminal

### Memory Leaks

Debug this potential memory leak.

Symptoms:

  • Memory grows over time
  • App becomes slower after extended use
  • [other symptoms]

Suspected code:

Terminal
[subscriptions, event listeners, timers]

Using Chrome DevTools, I see: [heap snapshot findings]

What's causing the leak and how do I fix it?

Terminal

## 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:

  1. [technical issue 1]
  2. [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
Terminal

## 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.
Mark this lesson as complete to track your progress