Real-World Patterns

All the techniques combined into concrete, repeatable workflows for the five tasks you do every day as a developer.

Intermediate 14 min read 5 patterns

Bug Fix Pattern

The most common task. Goal: locate, understand, and fix in the minimum number of focused calls.

Bug fix - step by step
Step 1 - Locate (new session)
  Prompt: "UserTest::testFindByEmail fails with 'Column not found: email_address'.
           Grep for 'email_address' in app/ to find where it is referenced."
  Tools:  Grep (pattern="email_address", path="app/")
  Tokens: ~300 input, ~150 output

Step 2 - Read targeted section
  Agent found: UserModel.php:89
  Prompt: "Read UserModel.php lines 82-100 (the findByEmail method)"
  Tools:  Read (offset=82, limit=18)
  Tokens: ~250 input, ~200 output

Step 3 - Fix
  Prompt: "The column is named 'email' not 'email_address' (schema: config/schema.sql:12).
           Fix line 91 only. Show the diff."
  Tools:  Edit
  Tokens: ~400 input, ~100 output (diff is small)

Step 4 - Verify
  Prompt: "Run UserTest::testFindByEmail"
  Tools:  Bash: composer test --filter testFindByEmail 2>&1 | tail -10
  Tokens: ~200 input, ~100 output

Total: ~1,150 tokens across 4 calls
Naive approach (dump all files, let agent explore): ~25,000 tokens
Saving: ~95%

Code Review Pattern

Focused reviews catch real bugs. Broad reviews produce long reports with mostly style suggestions.

Code review - focused prompt
Context: reviewing a pull request touching 3 files

Step 1 - Get the diff only (not the full files)
  git diff main...feature-branch -- app/services/BillingService.php | head -150
  Paste only the diff into the prompt

Step 2 - Targeted review prompt
  "Review this diff from BillingService.php.
   Report ONLY:
   - Logic bugs (wrong conditions, off-by-one, null handling)
   - Security issues (SQL injection, unvalidated input, exposed secrets)
   - Data integrity issues (missing transactions, race conditions)
   Skip: style, variable naming, refactoring suggestions, performance micro-opts.
   Format: bullet list, one line per issue, file:line reference."

Tokens: ~1,500 input (diff only, not full files), ~300 output
Naive (full file reads + open-ended review): ~8,000 input, ~1,500 output

Refactor Pattern

Refactoring generates large output if you let it. Constrain it to method-level chunks.

Refactor - method by method
Anti-pattern (expensive):
  "Refactor the entire UserController.php to use the repository pattern."
  -> Agent reads full file (4,000 tokens), outputs full rewrite (6,000 tokens)
  -> Total: ~12,000 tokens

Efficient approach (method by method):
  Session 1:
    "Extract the DB query in UserController::index() lines 22-35 to
     UserRepository::findPaginated(). Show diff for both files."
    -> Read lines 22-35 only, output diff (~150 tokens)

  Session 2:
    "Extract the email lookup in UserController::show() lines 52-60 to
     UserRepository::findByEmail(). The repository class is in app/repositories/."
    -> Same targeted approach

  Each session: ~800-1,200 tokens
  Full refactor (10 methods): ~10,000 tokens vs naive ~120,000 tokens

Test Writing Pattern

Write tests one class at a time using the existing test patterns as context.

Test writing - one class per call
Step 1 - Read the existing test for reference (once, cached)
  "Read tests/models/UserModelTest.php to understand the test pattern."
  -> ~800 tokens (read once, stays in context for the session)

Step 2 - Provide just the method signature to test
  "Write tests for PaymentModel::charge($amount, $card_token).
   Method is in app/models/PaymentModel.php lines 34-62.
   Test cases: valid charge, amount <= 0, invalid token, Stripe exception.
   Follow the same pattern as UserModelTest (already in context).
   Output: the test class only, no explanations."
  -> Read 28 lines of PaymentModel, output test class (~40 lines)
  -> ~1,200 tokens total

Step 3 - Run and fix if needed
  Bash: composer test -- tests/models/PaymentModelTest.php 2>&1 | tail -20
  -> Usually passes first try with focused context

Session total for one test class: ~2,500 tokens
Writing 10 test classes in sequence (cache stays warm): ~15,000 tokens total

New Feature Pattern

New features need careful decomposition. Use the layer split: model, controller, view, tests - each as a separate session.

Feature: add invoice PDF export
Session 1 - Model layer
  Context: InvoiceModel.php (current), schema.sql (relevant table)
  Task: "Add a generated_pdf_path column to invoices table.
         Add InvoiceModel::setPdfPath($path) and getPdfPath() methods.
         Show diff for model + new migration file only."
  Tokens: ~1,800

Session 2 - Service layer
  Context: diff from Session 1 (new method signatures), DomPDF docs snippet
  Task: "Create InvoicePdfService::generate(Invoice $invoice): string.
         Use DomPDF. Read template from /templates/invoice-pdf.html.
         Return saved file path. Show the new service class only."
  Tokens: ~2,200

Session 3 - Controller
  Context: InvoiceController.php lines 1-30 (class structure), new service class
  Task: "Add downloadPdf($id) action to InvoiceController.
         Use InvoicePdfService. Stream the file or redirect to storage URL.
         Show diff for controller only."
  Tokens: ~1,500

Session 4 - Tests
  Context: InvoiceServiceTest.php (pattern), new service from Session 2
  Task: "Write unit tests for InvoicePdfService::generate.
         Mock DomPDF. Test: valid invoice, missing template file, write error."
  Tokens: ~2,000

Total across 4 sessions: ~7,500 tokens
Monolith approach: ~60,000+ tokens (with worse output quality)

Quick Reference

Copy this into your CLAUDE.md or personal notes as a daily reminder:

Token efficiency quick reference
BEFORE EVERY SESSION:
  [ ] One task only. Write it in one sentence.
  [ ] Know which 1-3 files are involved before opening Claude Code.
  [ ] Start a new session (don't reuse unrelated history).

DURING THE SESSION:
  [ ] Grep first, then read targeted lines (not full files).
  [ ] Trim error messages to 10-15 relevant lines.
  [ ] Ask for diffs, not full file rewrites.
  [ ] Pipe Bash output: composer test 2>&1 | tail -30

PROMPT PATTERNS:
  Bug:     "In [file:lines], fix [error]. Constraint: [X]. Output: diff."
  Review:  "Review this diff. Report: bugs + security only. Skip: style."
  Feature: "Add [thing] to [file:lines]. Use [existing service]. Output: new code only."
  Tests:   "Test [Class::method]. Cases: [list]. Follow [ExistingTest.php] pattern."

CACHING RULES:
  [ ] System prompt + project docs = cache breakpoint
  [ ] Keep system prompt unchanged (any change = cache miss)
  [ ] Batch similar tasks in one session (cache stays warm)

NEVER:
  [ ] Don't read full files when a function is the target
  [ ] Don't ask "explain the whole codebase"
  [ ] Don't run Bash without piping output
  [ ] Don't mix unrelated tasks in one session
Build these as habits, not rules

You will not remember this checklist in every session. The goal is to internalize three instincts: (1) Grep before reading, (2) ask for diffs, (3) one task per session. Once those are automatic, the 50-70% token reduction happens without conscious effort. The rest of the techniques are optimizations on top.

You have completed the course!

You now have the full toolkit for token-efficient AI-assisted coding:

  • Token fundamentals and what silently inflates usage
  • Context management and CLAUDE.md design
  • Precise, surgical prompting patterns
  • Prompt caching with cache breakpoints
  • Task decomposition and parallel subagents
  • Targeted tool selection (Grep, Glob, Read with ranges)
  • Agentic workflow structure and session hygiene
  • Cost monitoring and budget guardrails
  • Five production-ready workflow patterns

Next: explore AI Agents for deeper agentic patterns, or Claude APIs for direct API integration.

PreviousCost Monitoring
Course completeAll 10 lessons done

Frequently Asked Questions

The bug fix pattern consistently delivers the highest savings because it is the most frequent task. By following Grep-first and diff-only output, a typical bug fix that might cost $0.15 in a naive approach costs $0.008-0.015 efficiently. Multiply by dozens of fixes per week and the savings compound quickly.

Start with three habits: (1) Grep before reading, (2) ask for diffs not rewrites, (3) start a new session for each task. These three changes alone typically reduce costs by 50-70%. Add prompt caching and task decomposition once those are muscle memory.

Use the Step split decomposition from the Task Decomposition lesson. First task: "Read the CLAUDE.md and directory structure. List which 3-5 files are most relevant to X." Second task: read only those files and do the work. The first task costs 1,000-2,000 tokens and prevents the 50,000-token exploration tax.

Yes - the principles apply to any LLM-based tool. The specific syntax differs: Cursor uses @-mentions for files, GitHub Copilot Chat uses #file references, Claude Code uses natural language tool calls. But the underlying principle - give the model only relevant context and constrain its output - works everywhere.