Replacing a conditional maze with strategy and adapter
Refactor a deeply nested conditional freight calculation engine into decoupled Strategy algorithms and an Adapter for third-party legacy APIs.
Contentsand lesson path
On this page
- The Anatomy of a Conditional Maze
- Executable Implementation: Strategy and Adapter in Python
- Measuring Complexity and Avoiding Pattern Overuse
Lessons of Design Patterns
- Patterns as named trade-offs: forces, solution, consequences Concept · 15 min
- Varying behavior: strategy, command and observer Concept · 25 min
- Shaping boundaries: adapter, facade and decorator Concept · 20 min
- Organizing domain logic and persistence: from transaction script to data mapper Concept · 25 min
- Replacing a conditional maze with strategy and adapter Lab · 30 min
- Pattern selection and overuse check Knowledge check · 8 questions
What you will learn
- Select a creational, structural or behavioral pattern for a stated design force and explain its consequences.
- Refactor toward or away from a pattern when it changes measured complexity, and recognize pattern overuse.
Prerequisites: Software Design Principles
01. The Anatomy of a Conditional Maze
In growing e-commerce platforms, shipping fee calculation is a notorious magnet for architectural decay. What begins as a clean ten-line function calculating standard domestic postage gradually accumulates layers of conditional logic: express rush surcharges, fragile handling fees, dimensional weight brackets, and third-party international carrier contracts.
Over time, this function metastasizes into a "conditional maze"—a monolithic procedure spanning hundreds of lines with cyclomatic complexity exceeding thirty. Multiple nested if/elif/else branches inspect raw string codes, query legacy external services, convert grams to pounds and cents to dollars inline, and throw untyped exceptions.
Every time logistics negotiations yield a new regional carrier or a seasonal rate adjustment, engineers must touch this fragile maze. A developer adding a Canadian express option accidentally breaks domestic standard shipping. Unit tests require hundreds of permutations to achieve branch coverage, and onboarding engineers struggle to trace the execution flow.
In this hands-on lab, we systematically dismantle a conditional shipping maze by applying two classic patterns: Strategy to isolate domestic calculation algorithms, and Adapter to reconcile an incompatible third-party carrier API.
The Architectural Refactoring Plan Refactoring code toward patterns must be disciplined and incremental rather than a speculative rewrite:
- 1. Define the Common Protocol: First, identify the core variation point and establish a uniform
ShippingRateStrategyprotocol that accepts a standardizedPackagevalue object and returns the rate in floating-point dollars. - 2. Extract Concrete Strategies: Extract domestic standard and express rate calculations into standalone strategy classes (
DomesticStandardStrategyandDomesticExpressStrategy). Each class encapsulates its own rate formula and constants. - 3. Reconcile Foreign Boundaries with Adapter: The international carrier operates via a legacy vendor API that expects weight in integer grams rather than kilograms, requires country ISO codes, and quotes prices in integer cents. Rather than polluting the shipping calculator with conversions, author a
CarrierApiAdapterthat implementsShippingRateStrategyand delegates translated parameters to the vendor API. - 4. Establish the Registry Calculator: Replace the hardcoded
if/elifmaze with aShippingCalculatorcontext that maintains a dictionary registry of strategies. New carriers and shipping options are registered at startup without modifying calculation routines.
Identifying the Code Smells in the Legacy Maze Before altering production code, architects catalog the specific design smells driving the refactoring:
- Primitive Obsession: The legacy routine passed raw tuples of
(float, str, float)rather than an immutable domain value object. Introducing the@dataclass(frozen=True) class Packagecreates an explicit type boundary. - Shotgun Surgery: Whenever rate brackets adjusted, developers had to modify the shipping calculator, update billing discount routines, and tweak fulfillment handlers. Encapsulating each rate algorithm inside a strategy isolates change propagation to a single file.
- Inappropriate Intimacy: The legacy shipping calculator directly converted kilograms to grams and dollars to cents to satisfy the international vendor API. Encapsulating these unit translations inside the
CarrierApiAdapterprevents third-party API quirks from leaking into the core domain.
02. Executable Implementation: Strategy and Adapter in Python
Review the complete, self-contained Python implementation below. Notice how the ShippingCalculator has zero compile-time knowledge of concrete calculation math or legacy vendor idiosyncrasies. It depends strictly on the ShippingRateStrategy protocol.
from dataclasses import dataclass
from typing import Protocol, Dict
@dataclass(frozen=True)
class Package:
weight_kg: float
destination_country: str
declared_value_usd: float
class ShippingRateStrategy(Protocol):
def calculate_rate(self, pkg: Package) -> float: ...
class DomesticStandardStrategy:
def calculate_rate(self, pkg: Package) -> float:
base = 5.0
return base + (pkg.weight_kg * 1.5)
class DomesticExpressStrategy:
def calculate_rate(self, pkg: Package) -> float:
base = 12.0
return base + (pkg.weight_kg * 3.0)
class InternationalCarrierLegacyApi:
"""Simulates an incompatible 3rd-party vendor API returning cents."""
def quote_freight_cents(self, grams: int, dest_iso: str) -> int:
if dest_iso == "CA":
return int(1500 + (grams * 0.02))
return int(2500 + (grams * 0.04))
class CarrierApiAdapter:
"""Adapts legacy freight API into ShippingRateStrategy protocol."""
def __init__(self, api: InternationalCarrierLegacyApi) -> None:
self._api = api
def calculate_rate(self, pkg: Package) -> float:
grams = int(pkg.weight_kg * 1000)
cents = self._api.quote_freight_cents(
grams, pkg.destination_country
)
return round(cents / 100.0, 2)
class ShippingCalculator:
def __init__(self) -> None:
self._strategies: Dict[str, ShippingRateStrategy] = {}
def register(self, code: str, strategy: ShippingRateStrategy) -> None:
self._strategies[code] = strategy
def compute(self, code: str, pkg: Package) -> float:
if code not in self._strategies:
raise ValueError(f"Unknown shipping option: {code}")
return self._strategies[code].calculate_rate(pkg)
def main() -> None:
calculator = ShippingCalculator()
calculator.register("DOM_STD", DomesticStandardStrategy())
calculator.register("DOM_EXP", DomesticExpressStrategy())
calculator.register(
"INT_AIR",
CarrierApiAdapter(InternationalCarrierLegacyApi())
)
pkg1 = Package(2.5, "US", 45.0)
pkg2 = Package(3.0, "CA", 120.0)
cost_std = calculator.compute("DOM_STD", pkg1)
cost_exp = calculator.compute("DOM_EXP", pkg1)
cost_int = calculator.compute("INT_AIR", pkg2)
print(f"Domestic Standard: ${cost_std:.2f}")
print(f"Domestic Express: ${cost_exp:.2f}")
print(f"International Air: ${cost_int:.2f}")
if __name__ == "__main__":
main()
Domestic Standard: $8.75
Domestic Express: $19.50
International Air: $15.60
03. Measuring Complexity and Avoiding Pattern Overuse
Measuring Refactoring Success How do we know this refactoring improved the architecture rather than simply shuffling lines of code? We measure concrete metrics before and after the change:
- Cyclomatic Complexity: The original monolithic calculation method had a cyclomatic complexity of 18. Following refactoring, the
compute()method has a complexity of 2, while each individual strategy class has a complexity of 1 or 2. - Localized Testability: Testing the international rate calculation no longer requires mocking domestic packages or navigating outer conditional guards. The
CarrierApiAdaptercan be verified in total isolation with lightweight unit tests. - Open/Closed Compliance: Adding a new freight carrier requires zero modifications to existing classes. A developer authors
FreightCarrierAdapterand registers it in the configuration bootstrap.
Contract Testing for Adapter Fidelity A critical operational concern when introducing Adapters over third-party APIs is contract drift. If the external vendor updates their JSON payload structure or redefines unit semantics without warning, the adapter can fail silently or yield distorted calculations in production.
To mitigate this risk, architects enforce Contract Testing. A contract test suite executes identical test vectors against both the in-memory adapter test double and the sandbox environment of the vendor API during nightly builds. This ensures that parameter conversions (such as grams to kilograms and cents to dollars) remain perfectly synchronized across vendor version updates.
Composition Root and Strategy Wiring
Notice where strategy instances are instantiated and wired into the ShippingCalculator. In enterprise applications, strategy registration should never take place inside business logic or controller handlers. Instead, strategies are registered inside the application's Composition Root—the centralized startup module where dependency injection containers assemble the object graph.
By centralizing registration in the Composition Root, environment-specific overrides (such as swapping real carrier network adapters for mock adapters during integration testing) become trivial configuration toggles. Furthermore, runtime telemetry wrappers and monitoring decorators can be transparently injected around strategies without altering either the calculator context or the concrete strategy implementations.
Recognizing Pattern Overuse Refactoring toward patterns is warranted when high cyclomatic complexity and frequent changes collide in the same module. However, architects must guard against reflexively converting every single conditional statement into Strategy objects.
If a business calculation has two stable branches that have not changed in three years and are thoroughly covered by existing unit tests, introducing Strategy protocols, registry dictionaries, and separate factory builders adds needless indirection. Patterns must justify their structural weight by reducing measured operational friction.
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.