Tutorials Clean Architecture & DDD Mastery

Specification Pattern: Encapsulating business rules

On this page

Reusable Logic

The Specification Pattern allows you to encapsulate a piece of business logic (usually a filter or validation rule) into a reusable class.

1. Solving the "Leaky Query"

Instead of writing .Where(o => o.IsPaid && o.Status == 2) in 5 different places, you create a PendingOrdersSpecification. You can then pass this specification to your repository. This ensures that the 'Definition' of a pending order is centralized in the Domain layer.

2. Logic Composition

Specifications can be combined using And(), Or(), and Not(). This allows you to build complex business rules out of simple, testable blocks. var spec = new OverdueSpec().And(new HighValueSpec());. It translates perfectly to EF Core Expression trees for high-performance database queries.

3. Architect Insight

Q: "When should I use Specifications?"

Architect Answer: "Use them when a boolean business rule is reused in multiple places (filtering a list, validating a single entity, or even determining if a discount applies). It prevents the 'Copy-Paste' of business logic and ensures your domain invariants are enforced consistently across the whole system."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Clean Architecture & DDD Mastery
Course syllabus
1. Architectural Patterns
2. Domain-Driven Design (DDD) Foundations
3. Advanced DDD Patterns
4. Implementing the Clean Layers
5. Patterns for Data & Logic
6. Enterprise Domain Challenges
7. Testing Clean Architecture
8. Real-World Case Study
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details