AI-Assisted Code Review

Practical Exercise 5

Hands-On

Use AI to review code for quality, security, and best practices

Practical Objectives

1

Review code for security vulnerabilities

2

Identify code smells and anti-patterns

3

Check for performance issues

4

Suggest improvements and refactoring

Task 1: Security Review

Review this login endpoint for security issues:

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

    # Check credentials
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    user = db.execute(query).fetchone()

    if user:
        session['user_id'] = user['id']
        session['role'] = user['role']
        return redirect('/dashboard')

    return f"Login failed for user: {username}", 401
Hint: Look for SQL injection, password handling, session security, and information disclosure.

Task 1: Security Review Prompt

Security Review PromptAct as a security engineer. Review this code for vulnerabilities: [paste the login code] Check for: 1. SQL Injection risks 2. Password storage/handling issues 3. Session management vulnerabilities 4. Information disclosure 5. Input validation problems 6. OWASP Top 10 issues For each issue found: - Explain the vulnerability - Show how it could be exploited - Provide a secure fix

Task 2: Identify Code Smells

Find the code smells in this class:

class OrderProcessor:
    def process(self, order_data, user_data, payment_data, shipping_data, discount_code,
                notify_email, notify_sms, priority, gift_wrap, gift_message):
        # Validate order
        if order_data['items'] and len(order_data['items']) > 0:
            for item in order_data['items']:
                if item['quantity'] > 0:
                    if item['price'] > 0:
                        pass  # valid

        # Calculate total (duplicated in 3 places)
        total = 0
        for item in order_data['items']:
            total += item['price'] * item['quantity']

        # Apply discount (same logic in CartService and CheckoutService)
        if discount_code == 'SAVE10':
            total = total * 0.9
        elif discount_code == 'SAVE20':
            total = total * 0.8
        elif discount_code == 'SAVE30':
            total = total * 0.7

        # ... 200 more lines
        return {"status": "ok", "total": total}

Task 2: Code Smell Analysis

Code Review PromptReview this code for code smells and anti-patterns: [paste the OrderProcessor code] Identify: 1. Long parameter lists 2. Deeply nested conditionals 3. Code duplication 4. Magic numbers/strings 5. God class / doing too much 6. Poor naming For each smell: - Name the pattern - Explain why it's problematic - Suggest refactoring approach

Expected Findings

Long parameter list (10 params), Arrow anti-pattern (nested ifs), DRY violation (discount logic), magic strings, God method

Task 3: Performance Review

Find performance issues in this code:

def get_user_orders(user_id):
    user = User.query.get(user_id)
    orders = []

    for order in Order.query.all():  # N+1 query problem
        if order.user_id == user_id:
            order_data = {
                'id': order.id,
                'items': [],
                'total': 0
            }
            for item in OrderItem.query.filter_by(order_id=order.id):  # Another N+1
                product = Product.query.get(item.product_id)  # Yet another query
                order_data['items'].append({
                    'name': product.name,
                    'price': product.price,
                    'quantity': item.quantity
                })
                order_data['total'] += product.price * item.quantity
            orders.append(order_data)

    return orders

Task 3: Performance Analysis Prompt

Performance Review PromptAct as a performance engineer. Analyze this database query code: [paste the get_user_orders code] Identify: 1. N+1 query problems 2. Unnecessary database calls 3. Missing indexes (assume standard schema) 4. Inefficient loops 5. Memory issues with large datasets For each issue: - Explain the performance impact - Estimate complexity (O notation) - Provide optimized solution with eager loading

Task 4: Comprehensive Review

Perform a full code review on your own project:

Comprehensive Review PromptReview this code as a senior developer would in a PR review: [paste your code - 50-100 lines] Evaluate against these criteria: 1. Correctness: Does it do what it's supposed to? 2. Security: Any vulnerabilities? 3. Performance: Any bottlenecks? 4. Readability: Is it clear and well-named? 5. Maintainability: Easy to modify later? 6. Testing: Is it testable? What tests are needed? 7. Error handling: Are failures handled gracefully? Provide specific, actionable feedback with code examples.

Deliverables Checklist

Security Fixes

  • Fixed SQL injection
  • Implemented password hashing
  • Secured session handling
  • Removed info disclosure

Code Quality

  • Identified 5+ code smells
  • Refactored long method
  • Extracted discount logic
  • Reduced parameter count

Performance

  • Fixed N+1 queries
  • Added eager loading
  • Optimized loop structure

Own Project

  • Reviewed own code with AI
  • Documented findings
  • Applied improvements

Review Complete!

You've learned AI-assisted code review

Next: Practical 6 - Refactoring Legacy Code

Slide Overview