Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Code review skill from a 146-skill marketplace of 112 specialized AI agents for Claude Code (Opus 4.6/Sonnet 4.6).
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2name: code-review-excellence3description: Master effective code review practices to provide constructive feedback, catch bugs early, and foster knowledge sharing while maintaining team morale. Use when reviewing pull requests, establishing review standards, or mentoring developers.4---56# Code Review Excellence78Transform code reviews from gatekeeping to knowledge sharing through constructive feedback, systematic analysis, and collaborative improvement.910## When to Use This Skill1112- Reviewing pull requests and code changes13- Establishing code review standards for teams14- Mentoring junior developers through reviews15- Conducting architecture reviews16- Creating review checklists and guidelines17- Improving team collaboration18- Reducing code review cycle time19- Maintaining code quality standards2021## Core Principles2223### 1. The Review Mindset2425**Goals of Code Review:**2627- Catch bugs and edge cases28- Ensure code maintainability29- Share knowledge across team30- Enforce coding standards31- Improve design and architecture32- Build team culture3334**Not the Goals:**3536- Show off knowledge37- Nitpick formatting (use linters)38- Block progress unnecessarily39- Rewrite to your preference4041### 2. Effective Feedback4243**Good Feedback is:**4445- Specific and actionable46- Educational, not judgmental47- Focused on the code, not the person48- Balanced (praise good work too)49- Prioritized (critical vs nice-to-have)5051```markdown52❌ Bad: "This is wrong."53✅ Good: "This could cause a race condition when multiple users54access simultaneously. Consider using a mutex here."5556❌ Bad: "Why didn't you use X pattern?"57✅ Good: "Have you considered the Repository pattern? It would58make this easier to test. Here's an example: [link]"5960❌ Bad: "Rename this variable."61✅ Good: "[nit] Consider `userCount` instead of `uc` for62clarity. Not blocking if you prefer to keep it."63```6465### 3. Review Scope6667**What to Review:**6869- Logic correctness and edge cases70- Security vulnerabilities71- Performance implications72- Test coverage and quality73- Error handling74- Documentation and comments75- API design and naming76- Architectural fit7778**What Not to Review Manually:**7980- Code formatting (use Prettier, Black, etc.)81- Import organization82- Linting violations83- Simple typos8485## Review Process8687### Phase 1: Context Gathering (2-3 minutes)8889```markdown90Before diving into code, understand:91921. Read PR description and linked issue932. Check PR size (>400 lines? Ask to split)943. Review CI/CD status (tests passing?)954. Understand the business requirement965. Note any relevant architectural decisions97```9899### Phase 2: High-Level Review (5-10 minutes)100101```markdown1021. **Architecture & Design**103- Does the solution fit the problem?104- Are there simpler approaches?105- Is it consistent with existing patterns?106- Will it scale?1071082. **File Organization**109- Are new files in the right places?110- Is code grouped logically?111- Are there duplicate files?1121133. **Testing Strategy**114- Are there tests?115- Do tests cover edge cases?116- Are tests readable?117```118119### Phase 3: Line-by-Line Review (10-20 minutes)120121```markdown122For each file:1231241. **Logic & Correctness**125- Edge cases handled?126- Off-by-one errors?127- Null/undefined checks?128- Race conditions?1291302. **Security**131- Input validation?132- SQL injection risks?133- XSS vulnerabilities?134- Sensitive data exposure?1351363. **Performance**137- N+1 queries?138- Unnecessary loops?139- Memory leaks?140- Blocking operations?1411424. **Maintainability**143- Clear variable names?144- Functions doing one thing?145- Complex code commented?146- Magic numbers extracted?147```148149### Phase 4: Summary & Decision (2-3 minutes)150151```markdown1521. Summarize key concerns1532. Highlight what you liked1543. Make clear decision:155- ✅ Approve156- 💬 Comment (minor suggestions)157- 🔄 Request Changes (must address)1584. Offer to pair if complex159```160161## Review Techniques162163### Technique 1: The Checklist Method164165```markdown166## Security Checklist167168- [ ] User input validated and sanitized169- [ ] SQL queries use parameterization170- [ ] Authentication/authorization checked171- [ ] Secrets not hardcoded172- [ ] Error messages don't leak info173174## Performance Checklist175176- [ ] No N+1 queries177- [ ] Database queries indexed178- [ ] Large lists paginated179- [ ] Expensive operations cached180- [ ] No blocking I/O in hot paths181182## Testing Checklist183184- [ ] Happy path tested185- [ ] Edge cases covered186- [ ] Error cases tested187- [ ] Test names are descriptive188- [ ] Tests are deterministic189```190191### Technique 2: The Question Approach192193Instead of stating problems, ask questions to encourage thinking:194195```markdown196❌ "This will fail if the list is empty."197✅ "What happens if `items` is an empty array?"198199❌ "You need error handling here."200✅ "How should this behave if the API call fails?"201202❌ "This is inefficient."203✅ "I see this loops through all users. Have we considered204the performance impact with 100k users?"205```206207### Technique 3: Suggest, Don't Command208209````markdown210## Use Collaborative Language211212❌ "You must change this to use async/await"213✅ "Suggestion: async/await might make this more readable:214`typescript215async function fetchUser(id: string) {216const user = await db.query('SELECT * FROM users WHERE id = ?', id);217return user;218}219`220What do you think?"221222❌ "Extract this into a function"223✅ "This logic appears in 3 places. Would it make sense to224extract it into a shared utility function?"225````226227### Technique 4: Differentiate Severity228229```markdown230Use labels to indicate priority:231232🔴 [blocking] - Must fix before merge233🟡 [important] - Should fix, discuss if disagree234🟢 [nit] - Nice to have, not blocking235💡 [suggestion] - Alternative approach to consider236📚 [learning] - Educational comment, no action needed237🎉 [praise] - Good work, keep it up!238239Example:240"🔴 [blocking] This SQL query is vulnerable to injection.241Please use parameterized queries."242243"🟢 [nit] Consider renaming `data` to `userData` for clarity."244245"🎉 [praise] Excellent test coverage! This will catch edge cases."246```247248## Language-Specific Patterns249250### Python Code Review251252```python253# Check for Python-specific issues254255# ❌ Mutable default arguments256def add_item(item, items=[]): # Bug! Shared across calls257items.append(item)258return items259260# ✅ Use None as default261def add_item(item, items=None):262if items is None:263items = []264items.append(item)265return items266267# ❌ Catching too broad268try:269result = risky_operation()270except: # Catches everything, even KeyboardInterrupt!271pass272273# ✅ Catch specific exceptions274try:275result = risky_operation()276except ValueError as e:277logger.error(f"Invalid value: {e}")278raise279280# ❌ Using mutable class attributes281class User:282permissions = [] # Shared across all instances!283284# ✅ Initialize in __init__285class User:286def __init__(self):287self.permissions = []288```289290### TypeScript/JavaScript Code Review291292```typescript293// Check for TypeScript-specific issues294295// ❌ Using any defeats type safety296function processData(data: any) { // Avoid any297return data.value;298}299300// ✅ Use proper types301interface DataPayload {302value: string;303}304function processData(data: DataPayload) {305return data.value;306}307308// ❌ Not handling async errors309async function fetchUser(id: string) {310const response = await fetch(`/api/users/${id}`);311return response.json(); // What if network fails?312}313314// ✅ Handle errors properly315async function fetchUser(id: string): Promise<User> {316try {317const response = await fetch(`/api/users/${id}`);318if (!response.ok) {319throw new Error(`HTTP ${response.status}`);320}321return await response.json();322} catch (error) {323console.error('Failed to fetch user:', error);324throw error;325}326}327328// ❌ Mutation of props329function UserProfile({ user }: Props) {330user.lastViewed = new Date(); // Mutating prop!331return <div>{user.name}</div>;332}333334// ✅ Don't mutate props335function UserProfile({ user, onView }: Props) {336useEffect(() => {337onView(user.id); // Notify parent to update338}, [user.id]);339return <div>{user.name}</div>;340}341```342343## Advanced Review Patterns344345### Pattern 1: Architectural Review346347```markdown348When reviewing significant changes:3493501. **Design Document First**351- For large features, request design doc before code352- Review design with team before implementation353- Agree on approach to avoid rework3543552. **Review in Stages**356- First PR: Core abstractions and interfaces357- Second PR: Implementation358- Third PR: Integration and tests359- Easier to review, faster to iterate3603613. **Consider Alternatives**362- "Have we considered using [pattern/library]?"363- "What's the tradeoff vs. the simpler approach?"364- "How will this evolve as requirements change?"365```366367### Pattern 2: Test Quality Review368369```typescript370// ❌ Poor test: Implementation detail testing371test('increments counter variable', () => {372const component = render(<Counter />);373const button = component.getByRole('button');374fireEvent.click(button);375expect(component.state.counter).toBe(1); // Testing internal state376});377378// ✅ Good test: Behavior testing379test('displays incremented count when clicked', () => {380render(<Counter />);381const button = screen.getByRole('button', { name: /increment/i });382fireEvent.click(button);383expect(screen.getByText('Count: 1')).toBeInTheDocument();384});385386// Review questions for tests:387// - Do tests describe behavior, not implementation?388// - Are test names clear and descriptive?389// - Do tests cover edge cases?390// - Are tests independent (no shared state)?391// - Can tests run in any order?392```393394### Pattern 3: Security Review395396```markdown397## Security Review Checklist398399### Authentication & Authorization400401- [ ] Is authentication required where needed?402- [ ] Are authorization checks before every action?403- [ ] Is JWT validation proper (signature, expiry)?404- [ ] Are API keys/secrets properly secured?405406### Input Validation407408- [ ] All user inputs validated?409- [ ] File uploads restricted (size, type)?410- [ ] SQL queries parameterized?411- [ ] XSS protection (escape output)?412413### Data Protection414415- [ ] Passwords hashed (bcrypt/argon2)?416- [ ] Sensitive data encrypted at rest?417- [ ] HTTPS enforced for sensitive data?418- [ ] PII handled according to regulations?419420### Common Vulnerabilities421422- [ ] No eval() or similar dynamic execution?423- [ ] No hardcoded secrets?424- [ ] CSRF protection for state-changing operations?425- [ ] Rate limiting on public endpoints?426```427428## Giving Difficult Feedback429430### Pattern: The Sandwich Method (Modified)431432```markdown433Traditional: Praise + Criticism + Praise (feels fake)434435Better: Context + Specific Issue + Helpful Solution436437Example:438"I noticed the payment processing logic is inline in the439controller. This makes it harder to test and reuse.440441[Specific Issue]442The calculateTotal() function mixes tax calculation,443discount logic, and database queries, making it difficult444to unit test and reason about.445446[Helpful Solution]447Could we extract this into a PaymentService class? That448would make it testable and reusable. I can pair with you449on this if helpful."450```451452### Handling Disagreements453454```markdown455When author disagrees with your feedback:4564571. **Seek to Understand**458"Help me understand your approach. What led you to459choose this pattern?"4604612. **Acknowledge Valid Points**462"That's a good point about X. I hadn't considered that."4634643. **Provide Data**465"I'm concerned about performance. Can we add a benchmark466to validate the approach?"4674684. **Escalate if Needed**469"Let's get [architect/senior dev] to weigh in on this."4704715. **Know When to Let Go**472If it's working and not a critical issue, approve it.473Perfection is the enemy of progress.474```475476## Best Practices4774781. **Review Promptly**: Within 24 hours, ideally same day4792. **Limit PR Size**: 200-400 lines max for effective review4803. **Review in Time Blocks**: 60 minutes max, take breaks4814. **Use Review Tools**: GitHub, GitLab, or dedicated tools4825. **Automate What You Can**: Linters, formatters, security scans4836. **Build Rapport**: Emoji, praise, and empathy matter4847. **Be Available**: Offer to pair on complex issues4858. **Learn from Others**: Review others' review comments486487## Common Pitfalls488489- **Perfectionism**: Blocking PRs for minor style preferences490- **Scope Creep**: "While you're at it, can you also..."491- **Inconsistency**: Different standards for different people492- **Delayed Reviews**: Letting PRs sit for days493- **Ghosting**: Requesting changes then disappearing494- **Rubber Stamping**: Approving without actually reviewing495- **Bike Shedding**: Debating trivial details extensively496497## Templates498499### PR Review Comment Template500501```markdown502## Summary503504[Brief overview of what was reviewed]505506## Strengths507508- [What was done well]509- [Good patterns or approaches]510511## Required Changes512513🔴 [Blocking issue 1]514🔴 [Blocking issue 2]515516## Suggestions517518💡 [Improvement 1]519💡 [Improvement 2]520521## Questions522523❓ [Clarification needed on X]524❓ [Alternative approach consideration]525526## Verdict527528✅ Approve after addressing required changes529```530