Skip to main content
Code review is essential for maintaining code quality, sharing knowledge, and catching bugs before they reach production. OpenHands can assist with code reviews by analyzing changes, identifying potential issues, and suggesting improvements.

Overview

OpenHands enhances your code review process by:
  • Automated analysis: Detecting bugs, security issues, and code smells
  • Standards enforcement: Checking adherence to coding guidelines
  • Improvement suggestions: Recommending better patterns and practices
  • Documentation: Generating summaries and explanations of changes

Automated Code Review

Code Quality Analysis

OpenHands can analyze code changes for quality issues:
Review the changes in this pull request for code quality:

1. Identify any code smells (long methods, deep nesting, etc.)
2. Check for proper error handling
3. Verify logging is appropriate and consistent
4. Look for potential memory leaks or resource handling issues
5. Assess test coverage of the changes
6. Rate overall code quality and explain your assessment
What OpenHands checks for:
CategoryIssues Detected
ComplexityLong methods, deep nesting, high cyclomatic complexity
MaintainabilityCode duplication, unclear naming, missing documentation
ReliabilityNull pointer risks, unhandled exceptions, race conditions
PerformanceN+1 queries, unnecessary allocations, inefficient algorithms

Style and Standards Enforcement

Ensure code follows your team’s standards:
Review this PR against our coding standards:

Standards document: docs/CODING_STANDARDS.md

Check for:
1. Naming convention compliance
2. File organization
3. Import ordering
4. Comment formatting
5. Consistent spacing and indentation
6. Required documentation presence
Example findings:
# Issue: Function name doesn't follow snake_case convention
def processUserData(data):  # Should be: process_user_data
    pass

# Issue: Missing docstring for public function
def calculate_total(items):
    # Add: """Calculate the total price of all items."""
    return sum(item.price for item in items)

Bug Detection

Identify potential bugs before they ship:
Analyze the code changes for potential bugs:

1. Logic errors and edge cases
2. Off-by-one errors
3. Null/undefined handling
4. Type mismatches
5. Concurrency issues
6. Resource cleanup problems

Provide specific line numbers and explanations for each issue found.
Common bug patterns detected:
# Bug: Inverted condition
if user.is_active:
    raise PermissionError("User is inactive")  # Wrong!

# Bug: Missing boundary check
def get_item(index):
    return items[index]  # No bounds checking

Review Assistance

Generating Review Comments

Get detailed review comments for a PR:
Generate code review comments for this pull request:

For each issue found, provide:
1. The file and line number
2. The severity (critical, major, minor, suggestion)
3. A clear explanation of the issue
4. A suggested fix with code example

Format the output as GitHub review comments.
Example output:
### src/api/users.py, line 45
**Severity**: Major

**Issue**: SQL injection vulnerability

The user input is interpolated directly into the SQL query without sanitization.

**Current code:**
query = f"SELECT * FROM users WHERE id = {user_id}"

**Suggested fix:**
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))

Identifying Potential Issues

Proactively find issues that might cause problems:
Review this PR and identify potential issues:

Categories to check:
1. Security vulnerabilities
2. Performance bottlenecks
3. Backwards compatibility breaks
4. Missing error handling
5. Test coverage gaps
6. Documentation needs

Rank issues by risk and effort to fix.

Suggesting Improvements

Get suggestions for making code better:
Suggest improvements for the code in this PR:

Focus on:
1. Cleaner, more idiomatic code
2. Better abstractions
3. Improved readability
4. Performance optimizations
5. More comprehensive testing
6. Enhanced documentation

For each suggestion, explain the benefit and show before/after code.
Example suggestion:
# Before: Nested conditionals
def process_order(order):
    if order.is_valid:
        if order.payment_confirmed:
            if order.items_in_stock:
                return ship_order(order)
    return None

# After: Early returns
def process_order(order):
    if not order.is_valid:
        return None
    if not order.payment_confirmed:
        return None
    if not order.items_in_stock:
        return None
    return ship_order(order)

Integration

GitHub Pull Request Integration

OpenHands integrates with GitHub for automated PR reviews:
  1. Install the GitHub App: See GitHub Integration
  2. Configure auto-review: Enable automatic review on PR creation
  3. Trigger manual reviews: Comment @openhands review on any PR
Automatic review workflow:
# .github/workflows/openhands-review.yml
name: OpenHands Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: openhands/review-action@v1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          review-type: comprehensive

GitLab Merge Request Integration

For GitLab users:
  1. Install the GitLab integration: See GitLab Integration
  2. Configure webhook triggers: Enable review on MR creation
  3. Manual trigger: Comment /openhands review on any MR

CI/CD Pipeline Integration

Add code review to your CI/CD pipeline:
- name: OpenHands Review
  uses: openhands/review-action@v1
  with:
    github-token: ${{ secrets.GITHUB_TOKEN }}
    fail-on: critical  # Fail CI if critical issues found

Best Practices

Effective Review Prompts

Write prompts that get useful reviews:
Review this PR with focus on:
- Security: We handle user PII in this code
- Performance: This runs in a hot path (1000+ calls/sec)
- Backwards compatibility: This is a public API

Context:
- This is a Python 3.11 project using FastAPI
- We follow PEP 8 and Google style docstrings
- Database is PostgreSQL with SQLAlchemy ORM

Ignore:
- Formatting issues (handled by pre-commit)
- Import ordering (handled by isort)

Combining Human and AI Review

Get the best of both worlds:
  1. First pass: OpenHands
    • Automated checks for common issues
    • Consistency verification
    • Initial quality assessment
  2. Second pass: Human reviewer
    • Architecture and design decisions
    • Business logic correctness
    • Knowledge transfer and mentoring
  3. Final pass: Author response
    • Address all feedback
    • Explain any disagreements
    • Request re-review if needed

Review Scope Guidelines

Change SizeRecommended Approach
Small (under 50 lines)Full automated review
Medium (50-200 lines)Automated + focused human review
Large (over 200 lines)Split PR or section-by-section review
RefactoringFocus on behavior preservation
New featureFocus on design and test coverage

Examples

Security-Focused Review

Perform a security review of this PR:

1. Check for injection vulnerabilities (SQL, XSS, command injection)
2. Verify authentication and authorization checks
3. Look for sensitive data exposure
4. Check cryptographic implementations
5. Verify input validation
6. Review error messages for information leakage

Rate each finding by CVSS severity and provide remediation steps.

Performance Review

Review this PR for performance:

Context: This code runs in our order processing pipeline 
handling 10,000 orders/minute.

Check for:
1. Database query efficiency (N+1, missing indexes)
2. Memory allocations in loops
3. Blocking operations that could be async
4. Caching opportunities
5. Algorithm complexity

Estimate the performance impact of any issues found.

API Review

Review this API change:

Check for:
1. RESTful design principles
2. Consistent naming and URL structure
3. Appropriate HTTP methods and status codes
4. Request/response validation
5. Error handling and error messages
6. API documentation completeness
7. Backwards compatibility with v1 clients