You add a CryptoPayout class, run the tests, and something fails because there is no CryptoPayoutValidator. You add that, and then a CryptoPayoutFeeCalculator, and then a branch in a factory that maps one to the other. That is parallel inheritance hierarchies: two or more class trees that grow in lockstep, where every subclass on one side needs a twin on the other.
It is a special case of shotgun surgery. One concept, a kind of payout, is spread across several hierarchies, so a single new variant means edits in several places. The usual giveaway is naming: if the subclass prefixes of one hierarchy match the prefixes of another, the two trees are probably describing the same variation twice.
Signs
How to spot it in a review.
- Subclasses in two hierarchies share the same prefixes, such as
BankPayoutandBankPayoutValidator. - Adding a subclass to one tree breaks the build or a test until you add its counterpart to another tree.
- A factory or
instanceofchain maps each class in one hierarchy to its partner in the other. - Methods in the second hierarchy downcast their argument to the matching subclass of the first.
- Code review comments like "you forgot the formatter for the new type" keep coming back.
What it looks like
A typical case, in three languages.
abstract class Payout {
constructor(readonly id: string, readonly amountCents: number) {}
}
class BankPayout extends Payout {
constructor(id: string, amountCents: number, readonly iban: string) {
super(id, amountCents);
}
}
class PayPalPayout extends Payout {
constructor(id: string, amountCents: number, readonly email: string) {
super(id, amountCents);
}
}
abstract class PayoutValidator<T extends Payout> {
validate(payout: T): string[] {
const errors: string[] = [];
if (payout.amountCents <= 0) errors.push("amount must be positive");
return errors.concat(this.validateDetails(payout));
}
protected abstract validateDetails(payout: T): string[];
}
class BankPayoutValidator extends PayoutValidator<BankPayout> {
protected validateDetails(payout: BankPayout): string[] {
return /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(payout.iban) ? [] : ["invalid IBAN"];
}
}
class PayPalPayoutValidator extends PayoutValidator<PayPalPayout> {
protected validateDetails(payout: PayPalPayout): string[] {
const errors = payout.email.includes("@") ? [] : ["invalid PayPal email"];
if (payout.amountCents > 1_000_000) errors.push("PayPal payouts are capped at 10,000.00");
return errors;
}
}
function validatePayout(payout: Payout): string[] {
if (payout instanceof BankPayout) return new BankPayoutValidator().validate(payout);
if (payout instanceof PayPalPayout) return new PayPalPayoutValidator().validate(payout);
throw new Error(`No validator for payout ${payout.id}`);
}
console.log(validatePayout(new PayPalPayout("po_311", 1_250_000, "ana@studio.io")));import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass
class Payout:
id: str
amount_cents: int
@dataclass
class BankPayout(Payout):
iban: str
@dataclass
class PayPalPayout(Payout):
email: str
class PayoutValidator(ABC):
def validate(self, payout: Payout) -> list[str]:
errors: list[str] = []
if payout.amount_cents <= 0:
errors.append("amount must be positive")
return errors + self.validate_details(payout)
@abstractmethod
def validate_details(self, payout: Payout) -> list[str]: ...
class BankPayoutValidator(PayoutValidator):
def validate_details(self, payout: BankPayout) -> list[str]:
if re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{11,30}", payout.iban):
return []
return ["invalid IBAN"]
class PayPalPayoutValidator(PayoutValidator):
def validate_details(self, payout: PayPalPayout) -> list[str]:
errors = [] if "@" in payout.email else ["invalid PayPal email"]
if payout.amount_cents > 1_000_000:
errors.append("PayPal payouts are capped at 10,000.00")
return errors
def validate_payout(payout: Payout) -> list[str]:
if isinstance(payout, BankPayout):
return BankPayoutValidator().validate(payout)
if isinstance(payout, PayPalPayout):
return PayPalPayoutValidator().validate(payout)
raise ValueError(f"No validator for payout {payout.id}")
print(validate_payout(PayPalPayout("po_311", 1_250_000, "ana@studio.io")))<?php
abstract class Payout
{
public function __construct(
public readonly string $id,
public readonly int $amountCents,
) {}
}
final class BankPayout extends Payout
{
public function __construct(string $id, int $amountCents, public readonly string $iban)
{
parent::__construct($id, $amountCents);
}
}
final class PayPalPayout extends Payout
{
public function __construct(string $id, int $amountCents, public readonly string $email)
{
parent::__construct($id, $amountCents);
}
}
abstract class PayoutValidator
{
public function validate(Payout $payout): array
{
$errors = [];
if ($payout->amountCents <= 0) {
$errors[] = 'amount must be positive';
}
return array_merge($errors, $this->validateDetails($payout));
}
abstract protected function validateDetails(Payout $payout): array;
}
final class BankPayoutValidator extends PayoutValidator
{
protected function validateDetails(Payout $payout): array
{
assert($payout instanceof BankPayout);
return preg_match('/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/', $payout->iban) ? [] : ['invalid IBAN'];
}
}
final class PayPalPayoutValidator extends PayoutValidator
{
protected function validateDetails(Payout $payout): array
{
assert($payout instanceof PayPalPayout);
$errors = str_contains($payout->email, '@') ? [] : ['invalid PayPal email'];
if ($payout->amountCents > 1_000_000) {
$errors[] = 'PayPal payouts are capped at 10,000.00';
}
return $errors;
}
}
function validatePayout(Payout $payout): array
{
return match (true) {
$payout instanceof BankPayout => (new BankPayoutValidator())->validate($payout),
$payout instanceof PayPalPayout => (new PayPalPayoutValidator())->validate($payout),
default => throw new InvalidArgumentException("No validator for payout {$payout->id}"),
};
}
print_r(validatePayout(new PayPalPayout('po_311', 1_250_000, 'ana@studio.io')));This is the payout module of a marketplace that pays sellers. Payout and PayoutValidator have identical subclass prefixes, each validator only works with its twin, and validatePayout exists purely to pair them up. When the team adds CryptoPayout with a wallet address, they must also write CryptoPayoutValidator and extend the dispatch, or every crypto payout throws at runtime. The fix is to move each validateDetails onto its payout subclass, keep the shared amount check in Payout.validate, and delete the validator tree and the dispatcher.
Why it happens
How code ends up like this.
- Every new variant costs edits in several files, and forgetting one only shows up at runtime as a missing-mapping error.
- The second hierarchy has to downcast or use generics to reach subclass-specific fields, so the type system protects you less than it appears to.
- Knowledge about one variant, such as the PayPal cap, is split between the data class and its partner, so readers have to jump between trees to understand it.
- The dispatch code mapping one hierarchy to the other is a type switch that grows with each variant and is easy to get out of sync.
Treatment
The refactorings that cure it, and when to choose each.
- Move Function: Put Behaviour Next to the Data It Uses
Move each method from the dependent hierarchy onto the matching subclass of the main one, for example
validateDetailsfromBankPayoutValidatorintoBankPayout, so the variant carries its own behaviour. - Inline Class: Fold a Class That No Longer Earns Its Keep
Once a partner class such as
PayPalPayoutValidatoris empty or only forwards calls, fold it away so only one hierarchy remains. - Replace Conditional with Polymorphism: One Class per Case
Replace the
instanceofchain ormatchthat pairs the two trees with a plain call likepayout.validate(), letting dynamic dispatch pick the right code. - Extract Class: Split a Class That Does Two Jobs
If the behaviour truly does not belong on the main class, extract it into one class that takes a small interface from the payout instead of one subclass per variant.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
When variants differ only in data like an IBAN or email format, wrap that value in its own type with validation, so new payout kinds reuse it without a new partner subclass.
Payoff
What you get once it's gone.
- Adding a payout kind touches one class instead of two or three plus a factory.
- No more runtime errors from a variant that has no partner registered.
- All rules for a variant live in one place, which makes reviews and onboarding faster.
- Downcasts and generic gymnastics disappear because behaviour sits next to the data it needs.
When to leave it
Sometimes it's not worth fixing.
- The second hierarchy sits in a different layer on purpose, such as persistence mappers or UI views, and merging it would drag database or rendering code into your domain model.
- The set of variants is closed and has not changed in a long time, so the duplicated structure costs little in practice.
- A framework or plugin system requires one class per type, for example serializers registered by class, and fighting it would cost more than the duplication.
Common questions
Short answers to the usual doubts.
How is this different from shotgun surgery?
It is a specific form of it. Shotgun surgery is any change that forces small edits across many places. Parallel inheritance hierarchies is the case where those places are subclasses in mirrored class trees, so the scattering is built into the class design rather than into random call sites.
Isn't putting validation on the payout class a violation of single responsibility?
Not necessarily. Rules about what makes a bank payout valid are part of what a bank payout is. If the logic depends on outside systems, like a fraud API, keep it out of the domain class and use one service that works through a small interface, not one subclass per payout type.
Is the Visitor pattern a case of parallel hierarchies?
Partly. A visitor needs a method per element type, so adding an element means touching every visitor. That is an accepted trade-off when element types are stable and operations change often. If element types change often, the trade-off flips and you should move behaviour onto the elements instead.
How would I explain this smell in an interview?
Name the symptom first: adding a subclass in one tree forces one in another, often visible through matching prefixes. Then describe the fix: move methods from the dependent tree onto the main one, inline the empty classes, and replace the type-mapping factory with polymorphism. Mention when you would keep the split, such as across architectural layers.
What if both hierarchies are genuinely large?
Move behaviour incrementally, one variant and one method at a time, with tests around the dispatcher. Once the partner class for a variant is empty, remove it and its branch. You do not need a big-bang rewrite to collapse the trees.