Domain-Driven Design (50 Qs)•Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
How do you model Complex Business Rules using the Specification Pattern?
senior LevelCode ExampleSystem Design
In Simple Words: Encapsulates a business rule or validation predicate into an independent, reusable boolean specification object:
- Allows chaining specifications using boolean logic (
and,or,not):
typescript
interface Specification<T> {
isSatisfiedBy(candidate: T): boolean;
and(other: Specification<T>): Specification<T>;
}
class CustomerEligibleForDiscountSpec implements Specification<Customer> {
isSatisfiedBy(customer: Customer): boolean {
return customer.accountAgeInYears >= 2 && customer.totalSpend > 5000;
}
}
- Can be used for in-memory entity validation, repository database query construction, or UI rule evaluation.