Untangling an order service one refactoring at a time
Refactor an entangled monolithic order service incrementally under test coverage, decomposing God classes into cohesive SRP domain modules and DIP interfaces.
Contentsand lesson path
On this page
- Diagnosing the Legacy God Class: The Entangled Order Service
- Worked Example: The Five-Phase Incremental Refactoring Strategy
- The Refactored Architecture: Cohesive and Inverted
- Practice check
- Review prompt
Lessons of Software Design Principles
- Why structure matters: paradigms, modules and the cost of change Concept · 20 min
- Measuring coupling with connascence Concept · 20 min
- SOLID, inversion of control and command-query separation Concept · 25 min
- Untangling an order service one refactoring at a time Worked example · 30 min
- When duplication beats the wrong abstraction Concept · 15 min
- Principles check: diagnose and justify Knowledge check · 8 questions
What you will learn
- Identify coupling and cohesion problems in a module and classify them by connascence type and strength.
- Apply SOLID principles to refactor a class design, stating which future change each refactoring makes cheaper.
01. Diagnosing the Legacy God Class: The Entangled Order Service
Almost every software engineer eventually encounters the quintessential enterprise anti-pattern: the God Class. In e-commerce backends, this manifested monster is almost invariably named OrderService or OrderManager. Over years of urgent sprint deadlines and feature requests, what began as a 50-line coordinating script grows into a 2,500-line labyrinth of tangled responsibilities.
Anatomy of an Architectural Nightmare
A typical legacy OrderService.processOrder() method performs dozens of unrelated tasks in a single sprawling execution flow:
- Parses raw HTTP JSON payloads and validates customer email strings.
- Executes raw SQL queries against PostgreSQL to verify product inventory counts.
- Directly instantiates third-party SDKs (e.g.,
stripe = StripeClient("sk_live_...")) and executes credit card charges. - Computes complex regional tax rules and promotional discount codes using nested
if/elseladders. - Mutates inventory tables, writes order records, and commits database transactions.
- Generates PDF invoices and connects directly to an SMTP server to transmit confirmation emails.
- Writes ad-hoc audit logs to local disk files.
Architectural Failure Modes This monolithic design exhibits catastrophic coupling across all dimensions:
- Zero Cohesion: The service serves five competing organizational stakeholders: Finance (tax and payments), Logistics (inventory reservation), Marketing (promotions), Customer Support (confirmation emails), and Infrastructure (audit logging). A change requested by Marketing risks causing payment capture outages.
- Strong Connascence of Meaning and Position: The method accepts seven positional arguments (including three booleans) and returns magic integer codes (
1for success,2for out of stock,3for card declined,4for SMTP timeout). - DIP Violation: High-level order fulfillment policy is tightly coupled to concrete third-party network APIs and database drivers, making unit testing without live network connections impossible.
Classic Code Smells: Divergent Change and Shotgun Surgery Martin Fowler classifies the twin architectural symptoms exhibited by this God class:
- Divergent Change: A single class suffers frequent, unrelated modifications by different teams for different business drivers (e.g., tax updates, shipping partner swaps, and email branding overhauls all touch
OrderService.ts). - Shotgun Surgery: Making a single conceptual business change forces developers to edit dozens of small methods scattered across multiple helper files.
- Dangerous Connascence of Timing: The legacy routine holds open an active PostgreSQL database transaction while executing a 3-second synchronous external HTTP call to Stripe. Under traffic spikes, slow third-party responses exhaust the enterprise database connection pool, causing cascading outages across the entire application.
02. Worked Example: The Five-Phase Incremental Refactoring Strategy
To dismantle a God class without disrupting production revenue, architects employ an incremental, step-by-step refactoring workflow:
Phase 1: Establish Characterization Tests (The Safety Net) As Michael Feathers establishes in Working Effectively with Legacy Code, code without tests is legacy code. Before modifying a single line of implementation, write characterization tests. Characterization tests do not assert what the code should do according to modern ideals; they assert what the legacy code actually does today, freezing current behavior (including legacy quirks) into a reliable regression harness.
Phase 2: Sprout Method and Extract Pure Domain Core When adding new functionality or untangling existing logic, use the Sprout Method and Wrap Method techniques. Rather than appending more code to a 300-line method, sprout a new, private pure function that computes the value independently. Isolate all calculation logic—such as subtotal summation, multi-tier tax calculation, and discount coupon evaluation—away from database calls and network requests. Move this calculation into pure domain functions or immutable value objects. This creates an instantly testable Functional Core.
Phase 3: Define Client-Owned Abstractions (DIP)
Identify external infrastructure boundaries and formulate minimal interfaces owned by the domain: PaymentGateway, InventoryService, and NotificationGateway. Replace direct constructor instantiations with constructor parameter injection. In tests, substitute in-memory fakes rather than brittle mocking libraries, allowing rapid deterministic testing of transient network failures and card declines.
Phase 4: Decompose by Stakeholder (SRP) and Domain Events
Separate invoice formatting and email transmission into dedicated event listeners or application services. When an order completes, publish an OrderPlaced domain event, allowing notification and analytics modules to react asynchronously without polluting the primary fulfillment transaction.
Phase 5: The Strangler Fig Rollout and Composition Root Rather than flipping a switch on all traffic at once, deploy the refactored service using the Strangler Fig Pattern. A lightweight routing proxy intercepts incoming traffic, directing 5% of order traffic to the refactored pipeline while observing error rates and latency in production. Once validated, traffic is progressively shifted until the legacy God class is safely excised.
03. The Refactored Architecture: Cohesive and Inverted
Following refactoring, the order fulfillment workflow is decoupled, cohesive, and fully testable in memory. High-level business orchestration depends solely on domain protocols, and side effects are cleanly isolated. The refactored service guarantees idempotency by accepting client-supplied transaction tokens, eliminating double-charge risks during network retries.
# Refactored Order Fulfillment Architecture
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class OrderRequest:
order_id: str
amount: float
customer_email: str
class PaymentGateway(Protocol):
def charge(self, order_id: str, amount: float) -> bool:
...
class InventoryClient(Protocol):
def reserve_items(self, order_id: str) -> bool:
...
class OrderFulfillmentService:
"""High-level orchestration policy obeying SRP and DIP."""
def __init__(
self, payment: PaymentGateway, inventory: InventoryClient
) -> None:
self._payment = payment
self._inventory = inventory
def fulfill(self, request: OrderRequest) -> bool:
if not self._inventory.reserve_items(request.order_id):
return False
if not self._payment.charge(request.order_id, request.amount):
return False
return True
class FakePaymentGateway:
def charge(self, order_id: str, amount: float) -> bool:
return True
class FakeInventoryClient:
def reserve_items(self, order_id: str) -> bool:
return True
service = OrderFulfillmentService(
payment=FakePaymentGateway(), inventory=FakeInventoryClient()
)
req = OrderRequest("ORD-101", 99.50, "[email protected]")
print(f"Order {req.order_id} fulfilled: {service.fulfill(req)}")04. Practice check
05. Review prompt
Describe the typical symptoms and architectural failure modes of a legacy God class (such as an unrefactored OrderService), identifying specific violations of Cohesion, Connascence, and SOLID principles.
Explain why Big Bang rewrites carry catastrophic risk, and articulate the economic advantages of incremental in-place refactoring under automated test coverage.
Detail the five phases of dismantling a God class: writing characterization tests, extracting pure domain calculations, defining client-owned DIP abstractions, decomposing by stakeholder responsibility, and wiring dependencies in the Composition Root.
Finally, explain how converting tight synchronous couplings into domain events (such as publishing OrderPlaced) insulates core fulfillment workflows from secondary notification and analytics failures.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.