Video in progress
What is the "parallel inheritance hierarchies" code smell and how do you fix it?
Every time you add a class to one hierarchy, you are forced to add its pair to another: CardPayment → CardPaymentValidator → CardPaymentMapper. It means the two hierarchies are tightly coupled, and every new type requires changes in several places.
📖 Answer
The typical picture:
Payment PaymentValidator PaymentDtoMapper
├─ CardPayment ├─ CardPaymentValidator ├─ CardPaymentDtoMapper
├─ BankTransfer ├─ BankTransferValidator ├─ BankTransferDtoMapper
└─ CashPayment └─ CashPaymentValidator └─ CashPaymentDtoMapper
Adding QrPayment means a new class in three places, and if you forget one, the error comes at runtime: "validator not found".
Solutions, depending on the situation:
-
Move the behavior into its own type. If validation is an internal rule of
Payment, it becomesCardPayment.validate(). One hierarchy remains. -
Sealed + an exhaustive
switch. When the validator or mapper has to stay in a separate layer (for example, the mapper lives in the API layer):
PaymentDto toDto(Payment p) {
return switch (p) {
case CardPayment c -> new CardDto(c.maskedPan());
case BankTransfer b -> new BankDto(b.iban());
case CashPayment c -> new CashDto();
};
}
When a new type is added, the compiler points at every switch, so forgetting one is impossible.
- Check the registration. If you use a
Map<Class<?>, Validator>in Spring, add a startup check or a test that asks "is there a validator for everyPaymenttype?"
Sometimes a parallel hierarchy is a conscious choice (for example, a separate domain model and persistence model). Even then, let the compiler or a test guarantee they match.
Sign up to mark studied questions and save your progress.