Polymorphism, Pure Fabrication, Indirection
Polymorphism, Pure Fabrication, Indirection (GRASP)
Three related GRASP principles that together give the architecture flexibility: – Polymorphism removes
if/elifbranching on types. – Pure Fabrication gives an artificial class when the domain does not have one. – Indirection adds a mediator between two sides to reduce coupling.
Polymorphism (a brief recap)
"When behaviour varies by type, push it into the types through a polymorphic method."
The GRASP form of the same idea you have already seen in OOP and OCP:
# ❌ Anti-pattern: if/elif on type
def calculate_area(shape):
if shape["type"] == "circle": return 3.14 * shape["r"] ** 2
elif shape["type"] == "square": return shape["side"] ** 2
# ✅ Polymorphism: each type implements the shared contract
class Shape(Protocol):
def area(self) -> float: ...
class Circle: def area(self): ...
class Square: def area(self): ...
This overlaps fully with OCP.
Pure Fabrication — an "invented" class for a responsibility
The idea
Sometimes you need to place a responsibility that does not belong to any natural domain class. So you invent a class — Repository, Service, Logger, Mapper, Factory — and give it that responsibility.
Pure Fabrication is an "artificial" class that exists only to solve a design problem. It has no direct counterpart in the real-world domain.
Why it is not a workaround for Information Expert
Information Expert says: "the function lives with the data". But:
Userhas the data for saving itself — but it should not know about SQL.Orderhas the data for notifying the customer — but it should not know about SMTP.Moneyhas an amount and a currency — but it should not know about exchange rates (that is separate logic).
In these cases the natural expert overloads itself with infrastructure or extra dependencies. Pure Fabrication takes that part out into a separate class that does not exist in the real world but makes sense in the code.
Classic Pure Fabrication examples
| Class | What "natural" expert would carry it? | What is excess |
|---|---|---|
UserRepository |
User would save itself |
SQL in the domain |
EmailNotifier |
Order.send_confirmation() |
SMTP in the domain |
PaymentGateway |
Customer.charge_card() |
Stripe API in the domain |
Logger |
Each service logs itself | Duplication |
PriceCalculator |
Order.calculate_price() |
Complex logic with external deps |
OrderToInvoiceMapper |
Order or Invoice converts itself |
Conversion is a separate concern |
Every service class in a Clean Architecture project (
RegisterUserService,CheckoutService,LegacyShippingAdapter) is a Pure Fabrication.
How to spot the need
If you ask yourself:
- "Where should this method go?
User? But that would turn User into a god class…" - "Many classes use this functionality — who should own it?"
- "This is a technical detail, not domain — where does it live?"
Then it is time for Pure Fabrication. Invent a class, name it by role (Notifier, Mapper, Calculator. Be careful with Manager).
Pure Fabrication anti-patterns
- Anemic Fabrication: you create
OrderManagerbut the real logic is still inOrder. You just added a useless layer. - Reusing the name "Service" for everything: five services with blurred boundaries. Ask "what does this service do?" and pick a sharper name (
PriceCalculator,OrderValidator). - Pure Fabrication for one method: a class with only one function can just be a function. Pure Fabrication is justified for a group of related responsibilities.
Indirection — a mediator between parties
The idea
When two components are tightly coupled directly, add a mediator that lowers the coupling.
Indirection is a mediator class that isolates two sides from each other.
"All problems in computer science can be solved by another level of indirection… except for the problem of too many levels of indirection." (David Wheeler). The second half matters as much as the first. Every wrapper has a cost.
Classic forms of Indirection
1. Adapter — a wrapper over an incompatible API
The most common case. You have a bad (legacy, third-party, awkward) API. You wrap it in a clean interface:
# A bad external API
class LegacyEmailAPI:
def SEND_MSG(self, params: dict) -> int:
# returns int (0=success, 1=fail), takes a dict with UPPER_KEYS
...
# Adapter — a clean interface
class EmailAdapter:
def __init__(self, legacy: LegacyEmailAPI):
self._legacy = legacy
def send(self, to: str, body: str) -> None:
result = self._legacy.SEND_MSG({"TO": to, "BODY": body})
if result != 0:
raise EmailDeliveryError()
# The domain uses the clean interface
class OrderService:
def __init__(self, email: EmailAdapter): ... # ← knows nothing about legacy
What Adapter gives you:
- Switching
LegacyEmailAPIfor modernSendGridlater means rewriting only the Adapter, not the domain. - Tests: pass in
FakeEmailAdapter. - The domain reads without dealing with legacy noise.
Adapter is both Pure Fabrication and Indirection at the same time: it does not belong to the domain, and it is a mediator.
2. Repository — a mediator between the domain and the DB
UserRepository is Indirection between RegisterUserService and Postgres / file / Redis.
3. Mediator (GoF) — a mediator between many parties
If A, B, C, D are mutually connected, you get six links in a cycle. A Mediator M puts itself in the middle:
BEFORE: A ─ B
|╲ ╱|
| × | 6 links between 4
|╱ ╲|
D ─ C
AFTER: A B
╲ ╱
M 4 links, none between components
╱ ╲
D C
The classic example: GUI components linked through a dialog controller (Mediator) rather than to each other.
4. Facade — a mediator that simplifies access to a subsystem
OrderSystem.checkout(...) internally calls five services. The client does not see five separate dependencies.
When NOT to use Indirection
Every level of indirection costs: another file, another abstraction, another step in the debugger.
Do not add Indirection "for the future":
# ❌ Useless wrapper
class StringPrinter:
def print(self, s):
print(s)
# Why not just call print() directly?
Indirection is justified when:
- There is a real need for isolation (testing, swapping the implementation, hiding complexity).
- There is more than one usage through the mediator.
- The low-level component is really volatile or complex.
Otherwise: YAGNI.
How the three principles work together
Look at a typical layered architecture:
┌───────────────────────────────────────────────────┐
│ Domain │
│ - Order (Information Expert) │
│ - PaymentGateway (Protocol) ← Indirection │
│ │
│ - CheckoutService ← Pure Fab │ no natural
│ (use case) │ domain class
│ │ for a use case
└──────────────────────┬────────────────────────────┘
↓
┌───────────────────────────────────────────────────┐
│ Infrastructure (adapters) │
│ - StripeGateway ← implements PaymentGateway │
│ (Polymorphism — any gateway is interchangeable) │
│ │
│ - LegacyStripeAdapter ← Indirection between old │
│ API and the new Protocol │
└───────────────────────────────────────────────────┘
- Polymorphism: different gateways are interchangeable through the Protocol.
- Pure Fabrication:
CheckoutServiceandPaymentGatewaydo not exist in the "real" domain, but the code needs them. - Indirection:
LegacyStripeAdapteris a mediator between the old API and the new contract.
The three together give the architecture flexibility without chaos.
Anti-patterns for all three
1. Pure Fabrication without a real role
class OrderHelperUtilityService:
def do_something(self): ...
If the name is a topical namespace with no clear role, this is not Pure Fabrication, it is a junk drawer. A Pure Fabrication name should describe a role: OrderValidator, PriceCalculator, CheckoutCoordinator.
2. Indirection with no reason
class StringContainer:
def __init__(self, s): self._s = s
def get(self): return self._s
# Instead of using `str` directly everywhere
Wrapping str in a class. What did that give you? Without validation, formatting, or normalisation, it is just noise.
3. Polymorphism for one type
class Animal(Protocol):
def speak(self): ...
class Dog:
def speak(self): print("woof")
# No Cat, Bird, or anything else is planned
YAGNI. Just class Dog: def bark(self): ....
4. Pure Fabrication that duplicates a natural class
class User:
def __init__(self, name, email): ...
class UserManager: # ← duplicates User's behaviour
def get_name(self, user): return user.name
def update_name(self, user, name): user.name = name
This is the "Service that does what User should do" anti-pattern. Move the methods into User.
Rules of thumb
if/elifon type means it is time for Polymorphism. With three branches or more.- "Where should I put this?" for non-domain logic means it is time for Pure Fabrication. Service, Adapter, Repository.
- Tight coupling between two sides means it is time for Indirection. Especially when one side is volatile.
- A Pure Fabrication name is a role.
OrderValidator, notOrderHelper.PaymentGateway, notPaymentManager. - Adapter is the standard form of Indirection for working with external APIs.
- Do not pile on extra layers. Indirection has a cost. Ask: "what does this really give us?"
- Pure Fabrication for one method is usually just a function. Crystallise into a class when you have two or three related methods.
One-line summary
Polymorphism removes branching on type. Pure Fabrication gives you an artificial class when the domain has none. Indirection adds a mediator so two sides do not know each other. All three are tools for reducing rigidity.