Design Patterns That Help Tame Legacy Code (With Python Examples)
Working with legacy code can feel like walking through a minefield. You know something might break, but you’re not sure when—or why. The good news is that design patterns can help.
In this post, I’ll share a few key design patterns that make working with legacy systems safer, cleaner, and more maintainable—using Python code examples.
🧩 1. The Adapter Pattern
Problem: Legacy code doesn't match the interface your modern code expects.
Solution: Wrap the old code in a new interface.
Example:
Let’s say you have a legacy payment gateway:
# legacy_system.py
class LegacyPaymentProcessor:
def make_payment(self, amount):
print(f"[Legacy] Processing payment of ${amount}")
Now, you want to use a modern interface:
# adapter.py
class PaymentInterface:
def pay(self, amount):
raise NotImplementedError
class LegacyAdapter(PaymentInterface):
def __init__(self, legacy_processor):
self.legacy_processor = legacy_processor
def pay(self, amount):
return self.legacy_processor.make_payment(amount)
Usage:
from legacy_system import LegacyPaymentProcessor
from adapter import LegacyAdapter
adapter = LegacyAdapter(LegacyPaymentProcessor())
adapter.pay(100)
✅ You can now use LegacyPaymentProcessor
anywhere PaymentInterface
is expected.
🏗️ 2. The Facade Pattern
Problem: Legacy subsystems are complex and hard to use.
Solution: Provide a simplified interface to a larger body of code.
Example:
# legacy_subsystem.py
class LegacyAuth:
def check_user(self, username, password):
return username == "admin" and password == "1234"
class LegacyLogger:
def log(self, msg):
print(f"[LOG]: {msg}")
Facade:
class AuthFacade:
def __init__(self):
self.auth = LegacyAuth()
self.logger = LegacyLogger()
def login(self, username, password):
if self.auth.check_user(username, password):
self.logger.log(f"{username} logged in.")
return True
self.logger.log("Invalid login attempt.")
return False
✅ Consumers don’t need to deal with the legacy details.
🧪 3. The Decorator Pattern
Problem: You want to add features without changing legacy code.
Solution: Wrap the legacy object to extend behavior dynamically.
Example:
class LegacyReporter:
def report(self):
print("Generating basic report...")
class TimestampedReporter:
def __init__(self, wrapped):
self.wrapped = wrapped
def report(self):
from datetime import datetime
print(f"Report generated at: {datetime.now()}")
self.wrapped.report()
Usage:
reporter = TimestampedReporter(LegacyReporter())
reporter.report()
✅ Legacy functionality extended without touching the original class.
🧰 4. The Strategy Pattern
Problem: You want to change algorithms used by legacy code without modifying it.
Solution: Inject behavior at runtime.
Example:
class LegacySorter:
def sort(self, data):
return sorted(data) # default
# New strategy
class ReverseSortStrategy:
def sort(self, data):
return sorted(data, reverse=True)
# Updated to accept strategy
class SorterContext:
def __init__(self, strategy):
self.strategy = strategy
def sort(self, data):
return self.strategy.sort(data)
Usage:
sorter = SorterContext(ReverseSortStrategy())
print(sorter.sort([5, 1, 4, 2]))
✅ Clean separation of algorithms for flexible extension.
🚦 5. The Proxy Pattern
Problem: You need to add access control, caching, or logging to legacy classes.
Solution: Create a stand-in object that controls access to the real one.
Example:
class LegacyDatabase:
def query(self, sql):
print(f"Executing SQL: {sql}")
return f"Results for: {sql}"
class LoggingProxy:
def __init__(self, db):
self.db = db
def query(self, sql):
print(f"[LOG] About to query: {sql}")
return self.db.query(sql)
✅ Seamless control over legacy components.
✨ Wrapping Up
Design patterns are not just academic tools—they’re powerful allies when refactoring or integrating legacy code. With Python’s dynamic capabilities, implementing these patterns becomes even more fluid and expressive.
When working with legacy systems, remember:
- Wrap, don’t rewrite (yet).
- Isolate risky code behind interfaces.
- Test as you refactor.
- Make your intentions clear with patterns.
Related Posts
- How AI Supercharges Accounting and Inventory in Odoo (with Dev Insights)
- Building a Fullstack E-commerce System with JavaScript
- Building Agentic AI with Python, Langchain, and Ollama for eCommerce & Factory Automation
- Diagnosing the Root Cause of P0420 with Python, OBD-II, and Live Sensor Data
- How to Apply The Mom Test to Validate Your Startup Idea the Right Way
- When to Choose Rasa vs Langchain for Building Chatbots
- Introducing OCR Document Manager: Extract Text from Documents with Ease
- Testing an AI Tool That Finds Winning Products Before They Trend — Interested?
- Your Website Is Losing Leads After Hours — Here’s the Fix
- How Agentic AI is Revolutionizing Smart Farming — And Why Your Farm Needs It Now
- How to Apply RAG Chatbot with LangChain + Ollama
- Automating EXFO Instruments with SCPI: A Practical Guide
- How to Safely Add New Features to Legacy Code — A Developer’s Guide
- Modernizing Legacy Software — Without Breaking Everything
- How OpenSearch Works — Architecture, Internals & Real-Time Search Explained
- Choosing the Right Strategy for Basic vs Premium Features in Django
- Transform Your Custom Furniture Business with a Modern eCommerce Platform
- Introducing simpliPOS: The Smart POS Built on ERPNext
- 🌾 Smart Farming Made Simple: A Tool to Help Farmers Track and Plan Inputs Efficiently
- Simulate Electromagnetic Waves with MEEP: A Hands-On Introduction
Our Products
Related Posts
- How AI Supercharges Accounting and Inventory in Odoo (with Dev Insights)
- Building a Fullstack E-commerce System with JavaScript
- Building Agentic AI with Python, Langchain, and Ollama for eCommerce & Factory Automation
- Diagnosing the Root Cause of P0420 with Python, OBD-II, and Live Sensor Data
- How to Apply The Mom Test to Validate Your Startup Idea the Right Way
- When to Choose Rasa vs Langchain for Building Chatbots
- Introducing OCR Document Manager: Extract Text from Documents with Ease
- Testing an AI Tool That Finds Winning Products Before They Trend — Interested?
- Your Website Is Losing Leads After Hours — Here’s the Fix
- How Agentic AI is Revolutionizing Smart Farming — And Why Your Farm Needs It Now
- How to Apply RAG Chatbot with LangChain + Ollama
- Automating EXFO Instruments with SCPI: A Practical Guide
- How to Safely Add New Features to Legacy Code — A Developer’s Guide
- Modernizing Legacy Software — Without Breaking Everything
- How OpenSearch Works — Architecture, Internals & Real-Time Search Explained
- Choosing the Right Strategy for Basic vs Premium Features in Django
- Transform Your Custom Furniture Business with a Modern eCommerce Platform
- Introducing simpliPOS: The Smart POS Built on ERPNext
- 🌾 Smart Farming Made Simple: A Tool to Help Farmers Track and Plan Inputs Efficiently
- Simulate Electromagnetic Waves with MEEP: A Hands-On Introduction