Skip to content
Legacy Code Reviewer logo

Legacy Code Reviewer

Expert system for identifying deprecated patterns, suggesting refactoring to modern standards (Python 3.12+, ES2024+), checking test coverage, and leveraging AI-powered tools. Proactively applied when users request refactoring, updates, or analysis of legacy codebases.

SKILL.md

Full skill instructions

Legacy Code Review and Refactoring Plan

Core Philosophy

Legacy code review is not just about finding bugs—it's about understanding the original intent, reducing technical debt, and incrementally modernizing while maintaining stability. Apply the principle: "Make it work, make it right, make it fast" in that order.


Instructions

1. Discovery & Analysis

Use Read, Grep, and Glob tools to:

  • Identify files referenced by the user
  • Search for deprecated APIs, patterns, or libraries (e.g., collections.MutableMapping → collections.abc.MutableMapping)
  • Detect code smells:
    • Unused imports/​functions (candidates for deletion)
    • Duplicated code blocks (refactor to DRY)
    • High cyclomatic complexity (McCabe > 10)
    • Missing type hints (Python) or JSDoc (JavaScript)

2. Modern Tooling Recommendations

Python Legacy Code (2024-2025 Best Practices):

ToolPurposeUsage
RuffUltra-fast linter + formatter (replaces Flake8, Black, isort)ruff check --fix .
VultureDead code detectionvulture src/
RefurbSuggests modern Python idiomsrefurb check src/
mypyStatic type checkingmypy --strict src/
BanditSecurity vulnerability scannerbandit -r src/
RadonComplexity metricsradon cc -s src/
pytest + coverageTest coverage analysispytest --cov=src tests/

JavaScript/​TypeScript Legacy Code:

ToolPurposeUsage
ESLint (with eslint-plugin-deprecation)Detect deprecated APIseslint --fix .
PrettierCode formattingprettier --write .
TypeScript CompilerType checking for TS/​JStsc --noEmit
ts-pruneDead code detectionts-prune
SonarQubeMulti-language code qualityCI/​CD integration

AI-Powered Code Review (GitHub Integration):

ToolKey Feature
GitHub CopilotSuggests refactorings, generates tests, explains legacy functions
CodeRabbitFull codebase context-aware reviews in PRs
Qodo.ai (Codium)AI test generation and quality checks
DeepSourceSecurity + performance analysis
GreptileSemantic code search across large repos

3. Refactoring Process (Step-by-Step)

[!IMPORTANT] Always write tests BEFORE refactoring. If no tests exist, create characterization tests first.

  1. Understand the Intent

    • Ask: "What problem was this solving?"
    • Review git history: git log --follow <file> and git blame <file>
    • Document assumptions in code comments
  2. Establish Safety Nets

    • Run existing tests: pytest tests/ (Python) or npm test (JS)
    • Measure current coverage: pytest --cov → target 80%+ for critical paths
    • Add characterization tests if coverage < 60%
  3. Incremental Refactoring (Layer by Layer)

    • Phase 1: Fix linting/​formatting (Ruff, Prettier) — low risk
    • Phase 2: Add type hints (mypy, TypeScript) — medium risk
    • Phase 3: Extract functions, reduce complexity — medium risk
    • Phase 4: Replace deprecated APIs with modern equivalents — high risk
    • Phase 5: Extract to new modules (strangler fig pattern) — high risk
  4. Verification Gates

    • All existing tests pass (pytest, npm test)
    • No new linting errors (ruff check, eslint)
    • Code coverage unchanged or improved (pytest --cov)
    • Security scan passes (bandit, npm audit)
  5. Documentation

    • Update docstrings with modern examples
    • Add inline comments explaining why, not what
    • Create migration guide if API changes affect users

4. Common Legacy Code Patterns (Python)

DeprecatedModern ReplacementReason
from collections import MutableMappingfrom collections.abc import MutableMappingMoved in Python 3.3+
os.path.join(a, b)pathlib.Path(a) / bType-safe, cleaner API
% formattingf"{variable}" or str.format()More readable, faster
try/​except without contextwith contextlib.suppress(Exception):Cleaner error handling
dict.has_key(k)k in dictPythonic, removed in Py3
No type hintsdef func(x: int) -> str:Catches bugs at dev time

5. GitHub Pull Request Best Practices (2024-2025)

[!TIP] Keep PRs small (<400 lines) for faster, more accurate reviews.

  • Small PRs: Break large refactors into atomic changes
  • Self-Review First: Review your own PR before requesting others
  • Automated Checks: Enforce linting, tests, security scans in CI/​CD
  • Clear Descriptions: Explain what, why, impact, how tested
  • Use Draft PRs: For work-in-progress, get early feedback
  • Feature Flags: For risky changes, use toggles to A/​B test old vs new logic

Output Format

Provide the following in your review:

  1. Summary of Findings

    • List deprecated patterns found (with line numbers)
    • Complexity metrics (if applicable)
    • Security vulnerabilities (if any)
  2. Recommended Tooling

    • Specific commands to run (e.g., ruff check --fix src/)
    • Expected output/​improvements
  3. Refactoring Plan (Phased)

    • Phase 1: Low-risk fixes (formatting, linting)
    • Phase 2: Medium-risk (type hints, small extractions)
    • Phase 3: High-risk (API migrations, architectural changes)
  4. Example Code Block

    • Show before and after code
    • Include comments explaining the change
    • Demonstrate modern conventions

Example Usage

User Request:

"Can you review @src/​legacy/​old_database_connector.py and suggest how to update it for better performance and maintainability?"

Agent Response:

Summary of Findings

  • Line 23: Using deprecated collections.MutableMapping (should be collections.abc.MutableMapping)
  • Line 45-67: Database connection logic duplicated 3 times (DRY violation)
  • Line 89: No type hints, making debugging difficult
  • Complexity: McCabe score of 15 (threshold is 10)

Recommended Tooling

# Run modern linters
ruff check --fix src/​legacy/​old_database_connector.py
mypy src/​legacy/​old_database_connector.py
bandit -r src/​legacy/

# Check complexity
radon cc -s src/​legacy/​old_database_connector.py

Refactoring Plan

Phase 1 (Low Risk):

  • Fix import: collections.MutableMapping → collections.abc.MutableMapping
  • Run Ruff to auto-fix formatting/​linting

Phase 2 (Medium Risk):

  • Add type hints to all functions
  • Extract duplicated connection logic to _get_db_connection() helper

Phase 3 (High Risk):

  • Replace raw SQL with SQLAlchemy ORM (if applicable)
  • Implement connection pooling for performance

Example Refactoring

Before (Legacy):

from collections import MutableMapping  # DEPRECATED

def connect_db(host, port):
    conn = psycopg2.connect(host=host, port=port)  # Duplicated 3 times
    return conn

After (Modern):

from collections.abc import MutableMapping
from typing import Optional
import psycopg2
from psycopg2 import pool

# Connection pool (shared resource)
_connection_pool: Optional[pool.SimpleConnectionPool] = None

def get_db_connection(host: str, port: int) -> psycopg2.extensions.connection:
    """
    Get a database connection from the pool.
    
    Args:
        host: Database host (e.g., 'localhost')
        port: Database port (e.g., 5432)
    
    Returns:
        Active database connection
    
    Raises:
        psycopg2.OperationalError: If connection fails
    """
    global _connection_pool
    if _connection_pool is None:
        _connection_pool = pool.SimpleConnectionPool(
            minconn=1, maxconn=10, host=host, port=port
        )
    return _connection_pool.getconn()

Key Improvements:

  • ✅ Fixed deprecated import
  • ✅ Added type hints (str, int, psycopg2.extensions.connection)
  • ✅ Extracted to single function (DRY)
  • ✅ Implemented connection pooling (performance)
  • ✅ Added comprehensive docstring

Verification Checklist

Before marking refactoring complete:

  • All existing tests pass
  • Linting passes (ruff check, eslint)
  • Type checking passes (mypy, tsc)
  • Security scan clean (bandit, npm audit)
  • Code coverage maintained or improved
  • Documentation updated
  • PR reviewed by at least one peer
  • Manual testing performed (if applicable)

Additional Resources

More Security skills

supabase logo
Security

supabase

Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...

2.7K 308.9K
View

Comprehensive guides and best practices for Neon Serverless Postgres, covering setup, connection methods, authentication, and platform APIs.

98 216.2K
View

Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.

462 163.8K
View

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

462 127.7K
View

Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.

462 125.1K
View

Complete Better Auth server and client setup with database adapters, session management, plugins, and security configuration.

222 118.2K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View
cloudflare logo
Security

cloudflare

Complete Cloudflare platform integration with decision trees for compute, storage, AI, networking, security, and infrastructure-as-code.

3K 110.7K
View

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

253 103K
View
gws-gmail logo
Security

gws-gmail

Send, read, and manage Gmail messages, drafts, labels, and account settings.

31.2K 78.9K
View

Comprehensive website auditing across 230+ rules in 21 categories including SEO, performance, security, and accessibility.

94 72.3K
View
gws-shared logo
Security

gws-shared

Shared authentication, CLI syntax, and output formatting patterns for gws Google Workspace commands.

31.2K 63.4K
View

Security AI tools

StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
GeoSpy logo
Security

GeoSpy

GeoSpy: Pricing, Features, FAQs, and Alternatives for AI Teams

Free
View

Detect AI-generated voices to protect against audio fraud.

Paid
View

Ensure Your Content's Originality with AI Plagiarism Checker

Freemium
View
Img Upscaler logo
Security

Img Upscaler

Upscale images by 400% without quality loss

Freemium
View
AICheatCheck logo
Security

AICheatCheck

Accurately Detect AI-Generated Content with TheChecker.AI

Free
View
D
Security

Detect GPT

Chrome extension that detects and flags AI-generated content

Free
View