Specification turns a business rule into an object with one question, isSatisfiedBy(candidate), and lets you combine rules with and, or and not into new rules. Instead of the same boolean expression typed into five services (and slowly drifting apart), the rule gets a name, lives in one place, and can be tested, reused and composed. Eric Evans and Martin Fowler described it in a paper of the same name, and Evans made it part of Domain-Driven Design (2003). It is not in the Gang of Four book.
Think of it like
A recipe card for "what counts"
A bakery's quality rule for its window display might read: "baked today, and not burnt, and either a bestseller or on special." The manager does not explain it again to every employee. It is written once on a card with a name, "window-worthy", and the person stocking the window, the person writing the online menu and the person doing the evening discount all check pastries against the same card. When the manager changes "baked today" to "baked in the last six hours", one card changes and everyone follows. Each line on the card is a small rule, and the card is those rules joined by "and", "or" and "not".
The problem
A shop marks some products as featured: price at least 100 and in stock. Two parts of the code need that rule. The catalog lists featured products, and checkout gives featured products free shipping. Without a home for the rule, each one types it out. This is the Before version in the visualizer above.
class Catalog {
list(ps: Product[]) {
return ps.filter((p) =>
p.price > 100 && // "at least 100"?
p.stock > 0);
}
}
class Checkout {
freeShipping(p: Product) {
// same rule, typed again
return p.price >= 100 &&
p.stock > 0;
}
}- The copies drift. One copy says
> 100, the other>= 100. A vase priced exactly 100 is not listed as featured, yet ships free. Nobody decided that; it happened because the rule was typed twice. - The rule has no name.
p.price >= 100 && p.stock > 0is a business concept ("featured") hiding as an expression. You cannot search for it, document it or ask a domain expert to review it. - Every change is a hunt. When "in stock" changes meaning, every copy must be found and edited the same way. Missing one is the drift above, again.
- Hard to test and to combine. The rule can only be tested through the service that contains it, and a new rule ("featured or on sale") means another hand-written expression.
The pattern
Intent: encapsulate a business rule in an object that answers whether a candidate satisfies it, and build complex rules by combining simple ones with logical operators. A rule becomes a value you can name, pass around, store and reuse.
- Specification (
Spec) - The abstraction:
isSatisfiedBy(candidate): boolean. In the visualizer it is an abstract class that also provides the fluentand(), so every spec can be combined. - Leaf specification (
PriceAtLeast,SoldOut) - Tests one fact about the candidate, often with a parameter (
new PriceAtLeast(100)). These are the named rules of the domain. - Composite specification (
AndSpec,OrSpec,NotSpec) - Holds other specifications and combines their answers with
&&,||or!. Written once, reused for every rule. - Candidate (
Product) - The object being checked. It knows nothing about the rules.
- Consumer (
Catalog,Checkout) - Code that needs an answer: it filters, validates or builds with a spec it was given, without knowing what the rule says.
Leaves and combinators share one interface, and combinators hold specs, so a composed rule is a tree: exactly the structure of Composite, applied to predicates. It is also a tiny boolean language whose sentences are object trees, which is the idea Interpreter develops into full grammars. You do not need either lesson to use Specification, but both explain why it works.
What the visualizer shows
- Building the rule. The client creates two leaves, wraps
soldOutin aNotSpecto getinStock, then callspremium.and(inStock).and()is inherited fromSpecand only builds anAndSpecnamedfeatured; nothing is evaluated yet. - One object, two consumers.
catalogandcheckouteach receivefeatured: in the Objects view bothrulefields point to the same box. - Evaluation as a tree walk. For
vase, the Sequence view showsisSatisfiedBy(vase)going fromcatalogtofeatured, down topremium, then toinStockand on tosoldOut, withtrue,false,trueandtruecoming back up. The captions show each leaf's test (100 >= 100is true) and theNotSpecflippingfalsetotrue. - Short-circuit. For
mug,premiumanswers false, andfeaturedreturns false at once:inStockandsoldOutget no message at all. - Before: no rule objects. The captions show the catalog testing
100 > 100(false) and checkout testing100 >= 100(true): the same vase, two answers.
Walkthrough
- 1
Name the facts
With With Specification selected, the client creates
premium(PriceAtLeast(100)) andsoldOut(SoldOut). Each is a leaf: one fact, one class, testable on its own. - 2
Combine, do not rewrite
inStockisnew NotSpec(soldOut): a rule built from a rule, with no new logic.premium.and(inStock)runs theand()inherited fromSpec, which createsfeatured, anAndSpecwhoseleftispremiumand whoserightisinStock. - 3
Hand the same rule to both consumers
new Catalog(featured)andnew Checkout(featured). Neither consumer contains a price or stock test any more. - 4
Selection
catalog.list([vase, mug])asksfeaturedabout each product. Forvasethe call descends the whole tree and returnstrue. Formug,premiumreturnsfalseand theAndSpecstops there. The list is[vase]. - 5
Validation
checkout.freeShipping(vase)asks the samefeaturedobject and walks the same tree:true. The two consumers cannot disagree, because there is only one rule. - 6
Change the rule
Apply Low stock: fewer than 3 left now counts as sold out. Only
SoldOut.isSatisfiedBy()changes (p.stock < 3). Rerun:soldOutanswerstrueforvase(2 left),NotSpecflips it tofalse, andvasedisappears from the list and loses free shipping.
Before and after
Rules as inline expressions
- The rule is retyped wherever it is needed, and copies drift (
> 100vs>= 100) - No name: the business concept is invisible in the code
- A change means finding and editing every copy
- Short, direct, and fine when a rule is used in exactly one place
With Specification
- One object per rule, shared by every consumer
- Named, unit-testable leaves (
PriceAtLeast,SoldOut) - New rules come from combining existing ones, not writing new code
- More classes, and evaluation happens in memory unless you also translate specs to queries
| Change request: fewer than 3 left counts as sold out | Before | With Specification |
|---|---|---|
| Existing classes edited | 2 (Catalog, Checkout) | 1 (SoldOut) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 4 (+2 −2) | 2 (+1 −1) |
Price drift (> 100 vs >= 100) | Still there | Impossible: one PriceAtLeast |
Variations
Fluent combinators and operators
Putting and(), or() and not() on the base type (an abstract class, or default methods on an interface) lets rules read left to right: premium.and(inStock).or(onSale). Languages with operator overloading go further: in Python, __and__, __or__ and __invert__ give premium & ~sold_out. Free functions (And(a, b), Not(a)) work too, as in the C++ version below. Whatever the syntax, a combinator only builds a new spec; nothing is evaluated until someone calls isSatisfiedBy.
A specification is a predicate
Strip the classes away and a specification is a function (x) => boolean, and and is just (a, b) => (x) => a(x) && b(x). In many codebases that is all you need. The class version earns its keep when you want more than the answer:
| Need | Plain predicate | Specification object |
|---|---|---|
| Reuse and combine | Yes, with higher-order functions | Yes, with and / or / not |
| A name in the domain model | A variable name only | A class (SoldOut) people can find, document and review |
| Metadata | None | Fields you can inspect: the threshold, a description, an error message for validation |
| Explain why it failed | Only false | Walk the tree and report which leaf failed |
| Translation to a query | Impossible: a compiled function cannot be read back | Possible: each node can produce a SQL condition (see below) |
Leaf and composite specifications
Leaves carry the domain knowledge; combinators are generic and written once. Keep leaves small and parameterized (PriceAtLeast(100) rather than PremiumProduct) when the threshold varies, and give important compositions their own name (const featured = ..., or a factory method Specs.featured()) so the rule still has one home. Specs should be immutable, which makes sharing one instance across consumers and threads safe.
Translating specifications to queries
Evaluating a spec in memory means loading the candidates first. Fine for 50 products in a cart, not for 5 million rows in a table. The answer is to let each node translate itself into the query language: a leaf emits price >= ? and a parameter, AndSpec joins its children with AND, NotSpec wraps with NOT (...). The second implementation below does exactly that and produces WHERE ((category = ? AND price >= ?) AND NOT (stock = 0)), so the database filters and can use its indexes (Database Indexing).
Three uses: validation, selection, building to order
- Validation: does this object meet the rule?
checkout.freeShipping(vase), or rejecting an order that failsOrderIsValid. - Selection: which objects meet it?
catalog.list(products)in memory, or a repository methodfindAll(spec)that translates it to a query. - Building to order: create something that meets it. Evans' example is a cargo-routing service that receives a specification of the required route and must produce one that satisfies it. The spec states what is needed; another object works out how.
In real code
| Where | What it is | Specification idea |
|---|---|---|
Java java.util.function.Predicate<T> | test(t) plus default and(), or(), negate() and static Predicate.not() (Java 11) | The predicate form: combinable rules without names or metadata |
Spring Data JPA Specification<T> | toPredicate(root, query, builder) builds a JPA Criteria condition; specs combine with where, and, or, not; repositories extending JpaSpecificationExecutor<T> offer findAll(spec) | Specifications translated to SQL by the ORM: selection in the database |
| .NET LINQ expression trees | A lambda typed as Expression<Func<T, bool>> is kept as a data structure, not compiled code, so a query provider such as Entity Framework can translate it to SQL | The same lambda can be compiled and run in memory, or translated: both evaluation paths from one rule |
| Validation rule engines | Libraries and business-rule engines that let you declare rules per field or object and combine them, then report which rules failed | Named rules plus metadata (messages, severity), evaluated for validation |
When to use it, and when not to
Reach for Specification when
- The same business rule is needed in several places (listing, validation, reporting, alerts)
- Rules are combined in many ways, or configured at run time (saved filters, admin-defined promotions)
- Domain experts talk about the rules by name and you want the code to match
- You need both in-memory checks and database queries from one definition
Skip it when
- A filter is used once:
products.filter((p) => p.stock > 0)is clearer than three classes - A plain predicate function already gives you the reuse you need
- Your ORM's query builder already expresses the condition and nobody reuses it
- The rule needs data the candidate does not have (it belongs in a service, not a spec)
Specification vs similar patterns
| Pattern | How it differs | Example |
|---|---|---|
| Strategy | A strategy is an interchangeable algorithm that does work; a specification is a yes/no rule, and specs are combined into trees rather than swapped one for another. A spec handed to a consumer does play a strategy-like role | PaymentStrategy.pay() vs featured.isSatisfiedBy(p) |
| Composite | Composite is the general structure (leaves and containers behind one interface); Specification is that structure specialized to boolean rules | Folder.size() sums children; AndSpec combines children with && |
| Interpreter | Interpreter represents a whole grammar as classes and evaluates sentences; Specification is a tiny fixed language (leaves, and, or, not) for one domain | An expression language with variables and operators vs premium.and(inStock) |
| Chain of Responsibility | A chain passes a request along until a handler takes it; a specification evaluates all relevant rules and combines their answers | Support escalation vs eligibility check |
| Query Object (Fowler) | An object that represents a database query and builds SQL from it; a specification that can translate itself to SQL overlaps with it, but a spec also evaluates in memory | new Query(Product).where(...) vs featured.toSql(params) |
Implementation
The scenario as a complete program: a generic specification with and, or and not combinators, leaf specs PriceAtLeast and SoldOut, and two consumers, Catalog and Checkout, that share the same featured rule. The demo then builds two more rules (restock and budget) from the same parts without writing a new class. Java uses default methods on an interface, Python uses the operators &, | and ~, and C++ uses free functions And, Or and Not over shared pointers.
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class Product:
name: str
price: int
stock: int
class Spec(ABC):
"""A business rule. &, | and ~ build new specs from existing ones."""
@abstractmethod
def is_satisfied_by(self, candidate) -> bool: ...
def __and__(self, other: "Spec") -> "Spec":
return AndSpec(self, other)
def __or__(self, other: "Spec") -> "Spec":
return OrSpec(self, other)
def __invert__(self) -> "Spec":
return NotSpec(self)
class AndSpec(Spec):
def __init__(self, left: Spec, right: Spec):
self.left, self.right = left, right
def is_satisfied_by(self, c) -> bool:
return (self.left.is_satisfied_by(c)
and self.right.is_satisfied_by(c))
class OrSpec(Spec):
def __init__(self, left: Spec, right: Spec):
self.left, self.right = left, right
def is_satisfied_by(self, c) -> bool:
return (self.left.is_satisfied_by(c)
or self.right.is_satisfied_by(c))
class NotSpec(Spec):
def __init__(self, spec: Spec):
self.spec = spec
def is_satisfied_by(self, c) -> bool:
return not self.spec.is_satisfied_by(c)
class PriceAtLeast(Spec):
def __init__(self, minimum: int):
self.minimum = minimum
def is_satisfied_by(self, p: Product) -> bool:
return p.price >= self.minimum
class SoldOut(Spec):
def is_satisfied_by(self, p: Product) -> bool:
return p.stock == 0
class Catalog:
def __init__(self, rule: Spec):
self.rule = rule
def list(self, products):
return [p for p in products if self.rule.is_satisfied_by(p)]
class Checkout:
def __init__(self, rule: Spec):
self.rule = rule
def free_shipping(self, p: Product) -> bool:
return self.rule.is_satisfied_by(p)
if __name__ == "__main__":
vase = Product("vase", 100, 2)
mug = Product("mug", 20, 5)
lamp = Product("lamp", 250, 0)
products = [vase, mug, lamp]
premium = PriceAtLeast(100)
in_stock = ~SoldOut()
featured = premium & in_stock
catalog = Catalog(featured)
checkout = Checkout(featured)
print([p.name for p in catalog.list(products)]) # ['vase']
print(checkout.free_shipping(vase)) # True
print(checkout.free_shipping(lamp)) # False
restock = premium & SoldOut()
budget = ~premium & in_stock
print([p.name for p in Catalog(restock).list(products)]) # ['lamp']
print([p.name for p in Catalog(budget).list(products)]) # ['mug']
print((restock | budget).is_satisfied_by(vase)) # FalseKey takeaways
- A specification is a business rule as an object:
isSatisfiedBy(candidate)returns true or false. - Leaves test one named fact;
AndSpec,OrSpecandNotSpeccombine specs, so a composed rule is a Composite tree evaluated top down, with short-circuiting. - One rule object shared by every consumer cannot drift. In the visualizer, changing what "sold out" means edits 1 class instead of 2, and the
> 100vs>= 100drift cannot happen. - Specifications serve validation, selection and building to order.
- Underneath it is a predicate. The class adds names, metadata, explanations and the ability to translate the rule into a query.
- Translating to SQL is the hard part: keep leaves simple, use parameters, and test both evaluators.
Common pitfalls
- Over-engineering: three classes for a filter used once. Start with a lambda.
- Filtering millions of rows in memory because the spec cannot be translated to a query, or loading everything to call
isSatisfiedBy. - In-memory and database evaluation that disagree (nulls, collation, time zones), so the list and the detail page give different answers.
- Leaves that reach out to services or the database inside
isSatisfiedBy: slow, hard to test, impossible to translate. Pass the data in with the candidate. - Mutable specs (a setter on the threshold) shared by several consumers: one consumer's change silently changes the others' rule.
Interview tips
- Start from the smell: the same boolean condition copied into several services, then show
isSatisfiedByplusand/or/not. - Draw it as Composite: abstract
Spec, leaves, combinators holding specs. Mention short-circuiting inAndSpec. - Bring up the database question yourself: in-memory evaluation vs translating to SQL, with Spring Data JPA
Specificationor LINQ expression trees as examples. - Say when you would not use it: a single, simple filter is better as a lambda or a
Predicate.
Real-world applications
- Product search filters and saved searches in e-commerce.
- Eligibility rules: promotions, free shipping, loan or insurance pre-qualification.
- Validation of domain objects with named, combinable rules and error messages.
- Repository queries built from criteria objects (Spring Data JPA specifications, LINQ).
- Access control and feature-flag targeting rules (user is in region and on plan X and not blocked).
- Alerting and monitoring conditions composed from simple checks.
Test yourself
In the visualizer, why are inStock and soldOut never called when the catalog checks mug?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.