Code refactoring example showing before/after improvements and bug fix
This repository demonstrates:
- Identifying and documenting a bug in production code
- Refactoring for clarity and maintainability
- Fixing the bug as part of the refactoring process
- Using modern Python patterns (dataclasses, type hints, Literal)
python-refactor-and-bugfix/
├── README.md
├── before.py # Original code with bug
└── after/
├── __init__.py
└── processor.py # Refactored code with bug fixed
Location: before.py lines 15-19
Issue: The code contains a logic error where pending status records are incorrectly skipped:
elif r["status"] == "pending":
# BUG: should count pending, but mistakenly continues and does nothing
if r["status"] != "pending": # This condition is always False!
pending += 1
continue # Skip without countingImpact: Pending records are never counted, resulting in pending: 0 in all reports.
The refactored version (after/processor.py) fixes the bug by:
- Simplifying the logic with a clean loop
- Using a dictionary to track counts by status
- Properly counting all status types
for r in records:
counts[r.status] += 1 # All statuses counted correctly
if r.status == "paid":
total_paid += r.amount- Dictionary-based records
- Manual variable tracking
- Complex if/elif logic
- Hidden bug in conditional
- Dataclasses with type safety
- Literal types for status validation
- Clean dictionary-based counting
- Bug eliminated by design
- Proper module structure
- Initial version with basic implementation - Original buggy code
- Refactor code for readability and structure - Clean refactoring
- Fix bug in pending status counting - Bug fix documentation
Before (with bug):
python before.py
# Output: {'total': 100.0, 'paid': 1, 'pending': 0, 'failed': 1}
# Notice pending is 0 (bug!)After (fixed):
python -m after.processor
# Output: {'total_paid': 100.0, 'counts': {'paid': 1, 'pending': 1, 'failed': 1}}
# Pending now counted correctly- ✅ Always test edge cases (like the "pending" status)
- ✅ Refactoring can reveal hidden bugs
- ✅ Modern Python features improve code safety
- ✅ Clear commit messages document the improvement process