Chapter 6 Code Best Practices: Generate & Review Code
6.1 The Generate-Review-Refine Workflow
Every time you ask Claude for code:
GENERATE → REVIEW → REFINE
Don’t use first answer immediately.
6.2 Phase 1: Generate
Ask Claude for code with full context:
Language: Python 3.10
Task: Function to calculate customer lifetime value
Requirements:
- Input: list of transaction amounts
- Output: single float (LTV)
- Exclude transactions: < $0, > $10000 (likely errors)
- Calculation: sum of valid transactions * 12 months
Example:
Input: [100, 150, 90, -50, 15000]
Output: 3420.0 (sum of [100,150,90] * 12)
6.3 Phase 2: Review - The Quality Checklist
After Claude generates code, ask yourself:
6.3.2 ✅ Is It Readable?
Good variable names?
# GOOD
def calculate_customer_ltv(transactions):
valid = [t for t in transactions if 0 <= t <= 10000]
return sum(valid) * 12
# BAD
def f(x):
y = [a for a in x if a > 0 and a < 10000]
return sum(y) * 12Clear logic?
6.3.3 ✅ Does It Handle Edge Cases?
Ask yourself: - What if input is empty? → errors or returns None? - What if input is invalid type? → crashes or handles gracefully? - What if numbers are very large? → overflow issues? - What if data is missing? → NaN/None handling?
Example:
# WORSE - no error handling
def calculate_ltv(transactions):
return sum(transactions) * 12
# BETTER - handles edge cases
def calculate_ltv(transactions):
"""Calculate customer lifetime value."""
if not transactions:
return None
if not isinstance(transactions, (list, tuple)):
raise TypeError("transactions must be list or tuple")
valid = [
t for t in transactions
if isinstance(t, (int, float)) and 0 <= t <= 10000
]
return sum(valid) * 12 if valid else None6.3.4 ✅ Is It Efficient?
- Does it make unnecessary loops?
- Could it use built-in functions?
- Will it work with large datasets?
6.3.5 ✅ Is It Documented?
# GOOD
def calculate_ltv(transactions: list[float]) -> float:
"""
Calculate customer lifetime value from transaction history.
Args:
transactions: List of transaction amounts (floats)
Returns:
float: Estimated annual value (sum * 12)
Raises:
TypeError: If transactions is not a list
Example:
>>> calculate_ltv([100, 150, 90])
4440.0
"""
...
# OKAY
def calculate_ltv(transactions):
# Returns annual LTV
return sum(transactions) * 12
# BAD
def f(x):
return sum(x) * 126.4 Phase 3: Refine
Ask Claude to improve it:
Good start! Can you:
1. Add error handling for edge cases
2. Add type hints
3. Add docstring with examples
4. Make it more efficient
5. Add logging for debugging
6.6 Common Code Problems Claude Might Miss
6.7 Asking Claude for Code Review
I have this function:
[paste code]
Code review:
1. Does it work correctly?
2. What edge cases am I missing?
3. How would you improve it?
4. Any performance concerns?
5. Any security concerns?