Protected Variations
“How to design objects, subsystems, and systems so that the variations or instability in these elements does not have an undesirable impact on other elements?” – Craig Larman
Identify points of predicted variation or instability; assign responsibilities to create a stable interface around them.
When to use
When you expect a part of the system/requirements to change (e.g., changing tax rules, changing DB vendor, changing UI framework).
Why it matters
- Stability: Protects the core system from the chaos of changing external requirements or volatile libraries.
- Cost: Reduces the cost of future changes.
Signs of Violation
- “Ripple Effect”: Changing one small thing breaks code in 10 other places.
- Hardcoded logic for things that change often (business rules, protocols).
Explanation
Problem
If you don’t wrap unstable parts, the instability infects your stable code.
Solution
Wrap the unstable concept in a stable Interface. The rest of the system talks to the stable interface. The implementation behind the interface can change (vary) as much as it wants without affecting the system.
Real world analogy
Standardized shipping containers. The crane doesn’t care if the container holds bananas or BMWs; the “interface” (corners, size) is stable/protected, even though the content varies.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- OCP (Solid): Protected Variations is essentially the root principle behind OCP. You protect the system from variations by allowing extensions.
- Polymorphism: The mechanism used to achieve Protected Variations.
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)