Protected Variations

Protected Variations (GRASP)

"Identify points of predicted variation or instability; assign responsibilities to create a stable interface around them." — Craig Larman, Applying UML and Patterns

"All the earlier principles are particular forms of Protected Variations. They are its architectural conclusion."


Core idea

Predict where your system will change, and ahead of time wrap those points behind a stable interface. Anywhere variation is not expected, do not protect (YAGNI).


Three steps of Protected Variations

Step 1: identify points of variation

Not every part of the system is equally volatile. Some are stable for decades (mathematics, basic data structures). Some change every month (integrations, business rules).

Classic sources of variation:

Source Example
External services Payment gateways, email providers, APIs
Data storage Postgres → MongoDB, file → S3
Business rules Discounts, tax rates, limits
Formats JSON → Protobuf, CSV → Parquet
Platform Linux → Windows, x86 → ARM
Localisation Language, currency, date format
Regulatory changes GDPR, PCI DSS, local laws

Step 2: wrap a stable interface

How exactly to "wrap" depends on the kind of variation:

Variation Mechanism
Behaviour varies by type Polymorphism (Protocol / ABC)
External integration Adapter (Pure Fabrication + Indirection)
Storage Repository
Algorithm or rule Strategy
An object that is a "big struct" Data Mapper
Complex construction Factory / Builder

This is the same toolbox that has appeared throughout this guide. Protected Variations is the lens that says "use these for isolating variation".

Step 3: implementations apart, abstraction apart

Intersects with DIP: the domain depends on the abstraction, the implementation is a separate component, and the Composition Root wires them together.


Is this the same as OCP?

OCP Protected Variations
"Result-based" — what the finished code looks like "Process-based" — how to arrive at such code
An engineering principle A design heuristic
Checked on existing code Applied at the start of design
Avoid modification, allow extension Predict what will change and isolate it ahead of time

In practice both lead to the same structures (Protocols, DI, composition). Protected Variations tells you when to build that design (at the start, while identifying variation), and OCP tells you how to check that you did it right.


The key anti-pattern: "Speculative Generality"

Premature generalisation for changes that will never happen — abstractions for a future that does not arrive.

Martin Fowler catalogues this smell in Refactoring (1999). The book does not rank it as "the second most common" — it is simply one of the most expensive, because you carry the abstraction for years with no reason.

# ❌ Speculative Generality:
class IStringConverter(Protocol):
    def convert(self, s: str) -> str: ...

class UppercaseConverter:
    def convert(self, s: str) -> str: return s.upper()

class TextProcessor:
    def __init__(self, converter: IStringConverter):
        self._converter = converter

Will there ever be another converter? If not, this is over-engineering. More code, more abstractions, more confusion, no real user.

How to avoid it

Ask before each Protocol:

  1. Are there two or more real implementations right now?
  2. Is a second one expected in the next 6-12 months?
  3. Is it worth doubling the code for a possibility that may never come?

If any answer is "no", do not extract the Protocol. If the implementation is one and stable, write it directly.

The best abstraction comes from two concrete cases, not from a prediction for one.


How to predict variation

1. Signal: it has already changed twice

If the VAT rate changed three times in five years, it is definitely a variation point. Protect it (through a TaxRate value object, config, or a separate table).

2. Signal: it is outside your control

An external company can shut off an API, change a format, change a licence. Use an Adapter.

3. Signal: it is used in several places

If the discount formula is in five places, you definitely want one place. Strategy + DI.

4. Signal: it is being discussed

If the team is talking about "let's add another provider", set up a Protocol now, even if the implementation is one (testability counts).

Red flags that variation will not come


An example of sensible balance

An order-processing system

Let us look at the variations:

Point Predictable variation? Protection
Order storage (Postgres → MongoDB?) Possibly, in a year OrderRepository Protocol
Payment gateway (Stripe → another vendor) Very likely PaymentGateway Protocol + Adapter
Email provider Possible EmailSender Protocol
Total-calculation formula (sum + discount) Stable for 10+ years Just Order.total()
Datetime formatting in logs Never changes f"{datetime.now().isoformat()}" directly
Serialising dict → JSON Standard json.dumps() directly
Pythagorean distance Stable for 2500 years Just the formula
Hash implementation Not allowed to change hashlib.sha256() directly

We protect the big, variable external things. We do not protect the math, the standard library, or formats that never change. That is the balance.


Protected Variations anti-patterns

1. Protect everything, just in case

class IDoubleAdder(Protocol):
    def add(self, a: float, b: float) -> float: ...

class StandardAdder:
    def add(self, a, b): return a + b

class Calculator:
    def __init__(self, adder: IDoubleAdder): ...

Full YAGNI. There will not be another way to add. This is Speculative Generality.

2. Protect nothing, react later

The other extreme: no Protocols, direct imports of external libraries into the business logic, no mocks. When the provider's API changes, half the code has to be rewritten.

3. Protect by inheritance — fragile base class

class Order:
    def total(self): ...

class SpecialOrder(Order):
    def total(self): ...

"Protection" through inheritance is a thin line. Some variation points can be protected this way (template method), but it tightly couples parent and child. Composition is almost always more flexible.

4. Configuration as protection (without limits)

config = {
    "discount_strategy": "percent",
    "tax_method": "vat",
    "rounding": "half_up",
    "currency_format": "{symbol}{amount}",
    ...
}

Hundreds of "future" settings, and none of them ever change. This is Speculative Generality with a config flavour.


Decision: protect, or not?

Ask in order:

  1. Is this external? (API, DB, file, environment). → Yes → protect.
  2. Is this a business rule set by people (not by mathematics)? → Yes → likely protect.
  3. Has this already changed at least once before? → Yes → protect.
  4. Is there a second real case right now? → Yes → protect.
  5. Is it planned for the next 3-6 months? → Yes → protect.

If the answer to all five is "no", do not protect.


A summary of all of SOLID + GRASP

All 14 principles (5 SOLID + 9 GRASP) are different views of one idea:

                     ┌─────────────────────────┐
                     │  Protected Variations   │ ← the goal: isolate change points
                     └────────┬────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
   "WHO HAS WHAT"      "HOW THINGS COUPLE"      "HOW TO CHANGE"
   - Info Expert        - Low Coupling          - OCP
   - Creator            - High Cohesion         - DIP
   - Controller         - Indirection           - LSP
                        - Pure Fabrication      - ISP
                        - Polymorphism          - SRP

All these principles are tools that help you isolate future changes.


Rules of thumb

  1. Predict based on real data: change history, team discussions, known plans.
  2. YAGNI on top of Protected Variations. Do not invent "ports" for imagined variations.
  3. Anything external is always protected. APIs, DBs, files, time, randomness.
  4. Internal math, standard library, basic utilities are not protected.
  5. Protocol is the cheapest form of protection in Python. Composition is the second.
  6. Do not confuse "a config parameter" with "a variation that needs an abstraction". Config is for small settings. Protocol is for varying behaviour.
  7. Protection is always justified by testability, even when there is one implementation.

One-line summary

Predict the real change points, wrap them in a stable interface, and do it only there. Everything else, write it directly.

This is the architectural summary of SOLID, GRASP, and design thinking in general.