Skip to content

Latest commit

 

History

History
473 lines (357 loc) · 10.1 KB

File metadata and controls

473 lines (357 loc) · 10.1 KB

Commented-Out Code - Delete, Don't Comment

The Problem

Commented-out code creates:

  • Confusion - Nobody knows if it's needed
  • Clutter - Makes code harder to read
  • Fear - "Someone left this for a reason..."
  • Bloat - Dead code taking up space
  • No context - Why was it commented? Is it safe to delete?

Bad Practice

function calculate_shipping($weight, $distance) {
    // return $weight * 0.5 + $distance * 0.1;
    // return ($weight * 0.6) + ($distance * 0.12);
    // return shipping_table_lookup($weight, $distance);
    return $weight * 0.55 + $distance * 0.11;
}

Questions:

  • Why were the other formulas tried?
  • Are they still relevant?
  • Can we delete them?
  • Which one is "correct"?

The Git History Problem

Here's the real issue: Commented code was often never used!

Fake Git History Example

Let's look at format_price() from bad.php:

$ git log --oneline format_price.php
abc123 Initial commit - Add price formatting
$ git show abc123
commit abc123def456
Date: 2023-06-15 10:30:00

Add price formatting function

+function format_price($price) {
+    // This was copied from another project
+    // $formatted = number_format($price, 2, ',', '.');
+    // return '€ ' . $formatted;
+    
+    // $formatted = '$' . number_format($price, 2);
+    // return $formatted;
+    
+    // Using WordPress formatting
+    return wc_price($price);
+}

Look closely! The commented code was:

  1. ✅ Added in the FIRST commit
  2. ❌ Never actually used
  3. ❌ Just copy-pasted and left there
  4. ⏰ Sitting there for 2.5 years

Another Example: The "Temporary" Disable

$ git log --follow validate_email.php
def456 Fix: Temporarily disable email verification
ghi789 Add email validation
$ git show def456
commit def456abc789
Date: 2023-05-20 14:22:00
Author: John Doe

Fix: Temporarily disable email verification

Causing too many false positives.
TODO: Re-enable after fixing

 function validate_email($email) {
     if (!is_email($email)) {
         return false;
     }
     
-    if (!verify_email_deliverable($email)) {
-        return false;
-    }
+    // Temporarily disabled - causes too many false positives
+    // if (!verify_email_deliverable($email)) {
+    //     return false;
+    // }
     
     return true;
 }

Date: May 20, 2023
Today: November 18, 2025
"Temporarily" disabled for: 2.5 years!

No follow-up commit. No ticket. No plan to fix.

The Debugging Code That Stayed

$ git log --oneline import_products.php
jkl012 Add product import
mno345 Fix import validation
pqr678 Debug: Add logging for import
$ git show pqr678
commit pqr678stu901
Date: 2024-05-10 09:15:00

Debug: Add logging for import

+function import_products($file) {
     $data = file_get_contents($file);
     $products = json_decode($data, true);
     
+    // echo '<pre>';
+    // print_r($products);
+    // echo '</pre>';
+    // die();
+    
     foreach ($products as $product) {

Never removed! Still there 6 months later.

Why This Happens

1. "Just in case"

Developers comment code "just in case we need it later."

Reality: If you need it, Git has it.

2. "Temporary" debugging

Debug code that never gets cleaned up.

Reality: Use proper logging, not commented print statements.

3. Copy-paste from other projects

Copying code blocks with alternatives already commented.

Reality: Clean up what you paste!

4. Fear of deleting

"Someone else wrote this, they must have had a reason."

Reality: If it's commented, it's not being used.

Good Practice

Delete, Don't Comment

// BAD: Commented alternatives
function calculate_shipping($weight, $distance) {
    // return $weight * 0.5 + $distance * 0.1;
    // return ($weight * 0.6) + ($distance * 0.12);
    return $weight * 0.55 + $distance * 0.11;
}

// GOOD: Current code only, history in Git
function calculate_shipping(float $weight, float $distance): float {
    // Formula based on carrier rate sheet v2.3 (updated 2024-11-01)
    return $weight * 0.55 + $distance * 0.11;
}

Git remembers everything:

$ git log --oneline calculate_shipping.php
abc123 Update shipping formula to v2.3
def456 Adjust for fuel surcharges
ghi789 Initial shipping calculation

Document Decisions, Not Code

// BAD: No explanation
function get_payment_gateway() {
    // return new PayPalGateway();
    // return new StripeGateway();
    return new SquareGateway();
}

// GOOD: Document why
function get_payment_gateway(): PaymentGatewayInterface {
    // Using Square gateway (switched 2024-08-01)
    // Previous gateways evaluated:
    // - PayPal: High fees
    // - Stripe: Limited country support for our market
    // Decision: docs/payments/gateway-selection.md
    return new SquareGateway();
}

Use Feature Flags, Not Comments

// BAD: Feature via comments
function show_dashboard() {
    // return render_new_dashboard();
    return render_old_dashboard();
}

// GOOD: Feature flag
function show_dashboard(): void {
    if ($this->features->is_enabled('new_dashboard')) {
        $this->render_new_dashboard();
    } else {
        $this->render_old_dashboard();
    }
}

Temporary Changes Need Tickets

// BAD: Vague "temporary"
// Temporarily disabled
// if (verify_email_deliverable($email)) { ... }

// GOOD: Documented temporary
// TODO: Re-enable deliverability check
// Ticket: #7890
// Disabled: 2024-05-15
// Reason: False positives for Gmail addresses
// Plan: Fix and re-enable by 2024-12-01

Common Excuses (And Why They're Wrong)

"What if we need it later?"

Git has it. That's what version control is for.

$ git log -p -- file.php  # See all changes
$ git show abc123:file.php  # See old version

"It shows what we tried"

Commit messages show that:

commit abc123
Date: 2024-01-15

Switch from Imagick to Cloudinary for image optimization

Tested alternatives:
- Imagick: Too slow (3s per image)
- GD Library: Poor quality (artifacts visible)
- Cloudinary: Fast (0.2s) with good quality

Decision based on benchmarks in #1234

"It's useful for reference"

Documentation is useful for reference:

Create docs/decisions/image-optimization.md:

# Image Optimization

## Decision: Use Cloudinary

### Alternatives Considered
1. **Imagick** - Too slow for our volume
2. **GD** - Quality issues
3. **Cloudinary** - Best balance

### Benchmarks
- Imagick: 3s per image
- GD: 0.5s but poor quality
- Cloudinary: 0.2s with excellent quality

### Implementation
See: `ImageOptimizer` class

What To Do Instead

1. Delete Dead Code

Press that delete key! Git has your back.

2. Write Commit Messages

Explain what changed and why:

commit abc123
Date: 2024-11-18

Remove old shipping calculation formula

The formula based on weight * 0.5 + distance * 0.1 was 
replaced with carrier rate sheet v2.3 which includes
fuel surcharges and zone-based pricing.

Old formula removed from code.
History available in Git.

Ticket: #5678

3. Use ADRs for Big Decisions

Architecture Decision Records document why:

# ADR 001: Use Transients for Caching

## Status
Accepted

## Context
Need caching for API responses.

## Decision
Use WordPress Transients API.

## Consequences
- Works everywhere
- Maximum 1 year TTL
- Auto cleanup

4. Link to Documentation

// Using Square gateway
// Selection criteria: docs/payments/gateway-selection.md
// Migration guide: docs/payments/square-migration.md

5. Use Standard Markers

// TODO: Add retry logic (ticket #123)
// FIXME: Handle edge case where user has no email
// NOTE: This assumes USD, update for multi-currency

Real-World Impact

Without Cleanup (Bad)

  • 200 lines of code
  • 80 lines are commented (40%!)
  • Takes 5 minutes to understand
  • Afraid to delete anything

With Cleanup (Good)

  • 120 lines of code
  • 0 lines commented
  • Takes 2 minutes to understand
  • Confident to modify

The Rule

If code is commented out:

  1. ❌ It's not being executed
  2. ❌ It's not being tested
  3. ❌ It's cluttering your codebase
  4. DELETE IT

Trust your tools:

  • Git remembers everything
  • Commit messages explain changes
  • Documentation provides context
  • Feature flags enable experiments

Key Takeaways

Delete commented code - Don't leave it
Trust Git - It remembers everything
Document decisions - Not code
Use feature flags - For experiments
Write good commits - Explain why
Add tickets/dates - For temporary changes
Create ADRs - For architecture decisions
Clean up after debugging - Remove debug code

❌ Don't comment out code "just in case"
❌ Don't leave "temporary" comments for years
❌ Don't copy-paste commented code
❌ Don't fear deleting code
❌ Don't use comments as version control
❌ Don't leave debug code commented
❌ Don't clutter with dead code

The Bottom Line

Commented code is dead code.

// This code is dead:
// function old_way() { ... }

// This code is alive and clear:
function current_way() { 
    // Proper documentation here
}

Delete fearlessly. Git remembers. Your team will thank you.

Bonus: How to Clean Up

Step 1: Find Commented Code

# Find all commented code
grep -r "^[[:space:]]*\/\/" . --include="*.php"

# Or use a tool
phpcs --standard=Squiz --sniffs=Squiz.PHP.CommentedOutCode

Step 2: For Each Comment, Ask:

  1. Is this active code with a comment? → Keep
  2. Is this commented-out code? → Delete
  3. Is this a TODO/FIXME with a ticket? → Keep (for now)
  4. Is this "temporary" from >6 months ago? → Delete

Step 3: Clean Your Git History

# See when code was commented
git log -p -S "// return old_value" -- file.php

# Find who commented it
git blame file.php

# Check if it was ever used
git log --all -- file.php | grep -v "commented"

Step 4: Make It a Habit

Add to code review checklist:

  • No commented-out code
  • No debug statements
  • TODOs have tickets
  • Decisions documented

Your codebase will thank you!