On this page

Specification Pattern

Specification isn't one of the original Gang of Four patterns. Eric Evans and Martin Fowler described it in the early 2000s, and it became a staple of domain-driven design. It answers a question every business application runs into: where should a rule like "eligible for free shipping" live, so that checkout, search and the nightly report all agree on what it means?

The answer is to make the rule an object. A specification is a predicate with a name, isSatisfiedBy(candidate), that can be combined with other specifications using and, or and not. This page is the LLD-focused, three-language companion to the longer DDD Specification Pattern deep dive. For the rest of the pattern catalogue, see the Design Patterns overview, and for its GoF cousins, Behavioral Patterns.

Intent

Encapsulate a business rule as a named, reusable predicate object that can be combined with other rules using boolean logic, and evaluated against any candidate object.

What that buys you:

  • One definition per rule. "Free-shipping eligible" is written once, as freeShipping(), and used by every caller.
  • Composition instead of new methods. New combinations are built from existing pieces (inStock().and(inCategory("books"))) rather than by writing a new method for each combination.
  • Three uses from one object. The same specification can validate an object ("is this product eligible?"), select objects ("find all eligible products") and, with some work, be translated into a query so the database does the filtering.

The problem

A catalogue service starts with a repository and a couple of services. Requirements trickle in, and each one gets its own method:

import java.util.List;

record Product(String sku, String category, long priceCents, int stock, double rating) {}

class ProductRepository {
    private final List<Product> rows;
    ProductRepository(List<Product> rows) { this.rows = rows; }

    List<Product> findInStockByCategory(String category) {
        return rows.stream().filter(p -> p.stock() > 0 && p.category().equals(category)).toList();
    }
    List<Product> findInStockByCategoryUnderPrice(String category, long maxCents) {
        return rows.stream().filter(p -> p.stock() > 0 && p.category().equals(category)
                                         && p.priceCents() <= maxCents).toList();
    }
    List<Product> findByCategoryRatedAtLeast(String category, double stars) {
        return rows.stream().filter(p -> p.category().equals(category) && p.rating() >= stars).toList();
    }
    // findInStockRatedAtLeastUnderPriceExcludingCategory(...) is next week's ticket
}

class CheckoutService {
    boolean freeShipping(Product p) {
        return p.stock() > 0 && p.priceCents() >= 5000 && !p.category().equals("furniture");
    }
}

class SearchService {
    boolean showFreeShippingBadge(Product p) {     // same rule, retyped by another team
        return p.stock() > 0 && p.priceCents() > 5000 && !p.category().equals("furniture");
    }
}

class BeforeDemo {
    public static void main(String[] args) {
        Product exactlyFifty = new Product("LAMP-1", "lighting", 5000, 3, 4.2);
        boolean atCheckout = new CheckoutService().freeShipping(exactlyFifty);
        boolean onSearchPage = new SearchService().showFreeShippingBadge(exactlyFifty);
        assert atCheckout && !onSearchPage;          // the two copies disagree
        System.out.println("checkout says " + atCheckout + ", search badge says " + onSearchPage);

        var repo = new ProductRepository(List.of(exactlyFifty));
        assert repo.findInStockByCategory("lighting").size() == 1;
    }
}

Two problems have grown together:

  • Combinatorial methods. Every new mix of conditions is a new repository method with a longer name. Four conditions already allow sixteen combinations, and nobody wants findInStockRatedAtLeastUnderPriceExcludingCategory.
  • Duplicated rules that drift. "Free shipping" lives in two services. One uses >=, the other >. A customer sees no badge on the search page for a $50.00 lamp, then gets free shipping at checkout. Nobody notices until a support ticket arrives, because each copy has its own tests.

Both have the same root cause: the business concepts ("in stock", "cheap", "free-shipping eligible") have no home of their own. They exist only as fragments of boolean expressions scattered through the code.

Structure

classDiagram
    class Specification~T~ {
        <<interface>>
        +isSatisfiedBy(candidate) boolean
        +and(other) Specification
        +or(other) Specification
        +not() Specification
    }
    class AndSpec~T~ {
        +left Specification
        +right Specification
    }
    class OrSpec~T~ {
        +left Specification
        +right Specification
    }
    class NotSpec~T~ {
        +inner Specification
    }
    class InCategory {
        +category String
    }
    class PriceAtMost {
        +cents long
    }
    class InStock
    class ProductRepository {
        <<interface>>
        +findMatching(spec) List
    }
    class CatalogRules {
        +freeShipping() Specification
        +budgetPicks(category) Specification
    }

    Specification <|.. AndSpec
    Specification <|.. OrSpec
    Specification <|.. NotSpec
    Specification <|.. InCategory
    Specification <|.. PriceAtMost
    Specification <|.. InStock
    AndSpec o-- Specification
    OrSpec o-- Specification
    NotSpec o-- Specification
    CatalogRules ..> Specification : composes
    ProductRepository ..> Specification : filters by

Participants

ParticipantIn the exampleResponsibility
SpecificationSpecification<T>Declares isSatisfiedBy and the and, or and not combinators.
Leaf specificationInCategory, PriceAtMost, PriceAtLeast, InStock, RatedAtLeastOne atomic business condition with its parameters.
Composite specificationAndSpec, OrSpec, NotSpecCombines other specifications with boolean logic. This is the Composite pattern applied to predicates.
Named ruleCatalogRules.freeShipping()A business concept built from leaves, given a name from the domain language. This is what services actually use.
CandidateProductThe object being tested.
RepositoryProductRepository.findMatching(spec)Accepts any specification instead of offering one method per combination.

Implementation

The three versions below share the same catalogue and the same two named rules: free shipping (in stock, at least $50.00, not furniture) and budget picks in a category (at most $20.00 and rated 4 stars or more). Prices are integer cents, never floating point.

import java.util.List;

record Product(String sku, String category, long priceCents, int stock, double rating) {}

interface Specification<T> {
    boolean isSatisfiedBy(T candidate);

    default Specification<T> and(Specification<T> other) { return new AndSpec<>(this, other); }
    default Specification<T> or(Specification<T> other) { return new OrSpec<>(this, other); }
    default Specification<T> not() { return new NotSpec<>(this); }
}

record AndSpec<T>(Specification<T> left, Specification<T> right) implements Specification<T> {
    public boolean isSatisfiedBy(T c) { return left.isSatisfiedBy(c) && right.isSatisfiedBy(c); }
    public String toString() { return "(" + left + " AND " + right + ")"; }
}

record OrSpec<T>(Specification<T> left, Specification<T> right) implements Specification<T> {
    public boolean isSatisfiedBy(T c) { return left.isSatisfiedBy(c) || right.isSatisfiedBy(c); }
    public String toString() { return "(" + left + " OR " + right + ")"; }
}

record NotSpec<T>(Specification<T> inner) implements Specification<T> {
    public boolean isSatisfiedBy(T c) { return !inner.isSatisfiedBy(c); }
    public String toString() { return "NOT " + inner; }
}

// Leaf specifications: one business condition each.
record InCategory(String category) implements Specification<Product> {
    public boolean isSatisfiedBy(Product p) { return p.category().equals(category); }
    public String toString() { return "category = " + category; }
}
record PriceAtMost(long cents) implements Specification<Product> {
    public boolean isSatisfiedBy(Product p) { return p.priceCents() <= cents; }
    public String toString() { return "price <= " + cents; }
}
record PriceAtLeast(long cents) implements Specification<Product> {
    public boolean isSatisfiedBy(Product p) { return p.priceCents() >= cents; }
    public String toString() { return "price >= " + cents; }
}
record InStock() implements Specification<Product> {
    public boolean isSatisfiedBy(Product p) { return p.stock() > 0; }
    public String toString() { return "in stock"; }
}
record RatedAtLeast(double stars) implements Specification<Product> {
    public boolean isSatisfiedBy(Product p) { return p.rating() >= stars; }
    public String toString() { return "rating >= " + stars; }
}

// Named business rules, defined once and used everywhere.
final class CatalogRules {
    private CatalogRules() {}

    static Specification<Product> freeShipping() {
        return new InStock().and(new PriceAtLeast(5000)).and(new InCategory("furniture").not());
    }

    static Specification<Product> budgetPicks(String category) {
        return new InCategory(category).and(new PriceAtMost(2000)).and(new RatedAtLeast(4.0));
    }
}

interface ProductRepository {
    List<Product> findMatching(Specification<Product> spec);
}

final class InMemoryProductRepository implements ProductRepository {
    private final List<Product> products;
    InMemoryProductRepository(List<Product> products) { this.products = List.copyOf(products); }

    public List<Product> findMatching(Specification<Product> spec) {
        return products.stream().filter(spec::isSatisfiedBy).toList();
    }
}

class SpecificationDemo {
    static List<String> skus(List<Product> ps) { return ps.stream().map(Product::sku).toList(); }

    public static void main(String[] args) {
        ProductRepository repo = new InMemoryProductRepository(List.of(
            new Product("LAMP-1", "lighting", 5000, 3, 4.2),
            new Product("SOFA-9", "furniture", 89900, 1, 4.8),
            new Product("BOOK-7", "books", 1500, 12, 4.6),
            new Product("BOOK-8", "books", 1800, 0, 4.9),
            new Product("BOOK-9", "books", 1200, 5, 3.1)));

        // Selection: the same rule drives search results...
        assert skus(repo.findMatching(CatalogRules.freeShipping())).equals(List.of("LAMP-1"));
        assert skus(repo.findMatching(CatalogRules.budgetPicks("books"))).equals(List.of("BOOK-7", "BOOK-8"));

        // ...and ad-hoc combinations need no new repository method.
        var budgetBooksInStock = CatalogRules.budgetPicks("books").and(new InStock());
        assert skus(repo.findMatching(budgetBooksInStock)).equals(List.of("BOOK-7"));

        // Validation: checkout asks the very same object about one product.
        var lamp = new Product("LAMP-1", "lighting", 5000, 3, 4.2);
        assert CatalogRules.freeShipping().isSatisfiedBy(lamp);

        System.out.println(CatalogRules.freeShipping());
    }
}
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass


@dataclass(frozen=True)
class Product:
    sku: str
    category: str
    price_cents: int
    stock: int
    rating: float


class Specification[T](ABC):
    @abstractmethod
    def is_satisfied_by(self, candidate: T) -> bool: ...

    # Python lets the combinators read like boolean algebra: a & b, a | b, ~a
    def __and__(self, other: Specification[T]) -> Specification[T]:
        return AndSpec(self, other)

    def __or__(self, other: Specification[T]) -> Specification[T]:
        return OrSpec(self, other)

    def __invert__(self) -> Specification[T]:
        return NotSpec(self)


@dataclass(frozen=True)
class AndSpec[T](Specification[T]):
    left: Specification[T]
    right: Specification[T]

    def is_satisfied_by(self, c: T) -> bool:
        return self.left.is_satisfied_by(c) and self.right.is_satisfied_by(c)


@dataclass(frozen=True)
class OrSpec[T](Specification[T]):
    left: Specification[T]
    right: Specification[T]

    def is_satisfied_by(self, c: T) -> bool:
        return self.left.is_satisfied_by(c) or self.right.is_satisfied_by(c)


@dataclass(frozen=True)
class NotSpec[T](Specification[T]):
    inner: Specification[T]

    def is_satisfied_by(self, c: T) -> bool:
        return not self.inner.is_satisfied_by(c)


@dataclass(frozen=True)
class InCategory(Specification[Product]):
    category: str
    def is_satisfied_by(self, p: Product) -> bool:
        return p.category == self.category


@dataclass(frozen=True)
class PriceAtMost(Specification[Product]):
    cents: int
    def is_satisfied_by(self, p: Product) -> bool:
        return p.price_cents <= self.cents


@dataclass(frozen=True)
class PriceAtLeast(Specification[Product]):
    cents: int
    def is_satisfied_by(self, p: Product) -> bool:
        return p.price_cents >= self.cents


@dataclass(frozen=True)
class InStock(Specification[Product]):
    def is_satisfied_by(self, p: Product) -> bool:
        return p.stock > 0


@dataclass(frozen=True)
class RatedAtLeast(Specification[Product]):
    stars: float
    def is_satisfied_by(self, p: Product) -> bool:
        return p.rating >= self.stars


def free_shipping() -> Specification[Product]:
    return InStock() & PriceAtLeast(5000) & ~InCategory("furniture")


def budget_picks(category: str) -> Specification[Product]:
    return InCategory(category) & PriceAtMost(2000) & RatedAtLeast(4.0)


class InMemoryProductRepository:
    def __init__(self, products: list[Product]) -> None:
        self._products = list(products)

    def find_matching(self, spec: Specification[Product]) -> list[Product]:
        return [p for p in self._products if spec.is_satisfied_by(p)]


if __name__ == "__main__":
    repo = InMemoryProductRepository([
        Product("LAMP-1", "lighting", 5000, 3, 4.2),
        Product("SOFA-9", "furniture", 89900, 1, 4.8),
        Product("BOOK-7", "books", 1500, 12, 4.6),
        Product("BOOK-8", "books", 1800, 0, 4.9),
        Product("BOOK-9", "books", 1200, 5, 3.1),
    ])

    def skus(ps: list[Product]) -> list[str]:
        return [p.sku for p in ps]

    assert skus(repo.find_matching(free_shipping())) == ["LAMP-1"]
    assert skus(repo.find_matching(budget_picks("books"))) == ["BOOK-7", "BOOK-8"]
    assert skus(repo.find_matching(budget_picks("books") & InStock())) == ["BOOK-7"]

    lamp = Product("LAMP-1", "lighting", 5000, 3, 4.2)
    assert free_shipping().is_satisfied_by(lamp)

    # Frozen dataclasses give value equality, so two independently built rules compare equal.
    assert free_shipping() == free_shipping()
    print("specification ok")
function assert(cond: unknown, msg = "assertion failed"): asserts cond {
  if (!cond) throw new Error(msg);
}

interface Product {
  readonly sku: string;
  readonly category: string;
  readonly priceCents: number;
  readonly stock: number;
  readonly rating: number;
}

abstract class Specification<T> {
  abstract isSatisfiedBy(candidate: T): boolean;
  abstract toString(): string;

  and(other: Specification<T>): Specification<T> { return new AndSpec(this, other); }
  or(other: Specification<T>): Specification<T> { return new OrSpec(this, other); }
  not(): Specification<T> { return new NotSpec(this); }
}

class AndSpec<T> extends Specification<T> {
  constructor(readonly left: Specification<T>, readonly right: Specification<T>) { super(); }
  isSatisfiedBy(c: T): boolean { return this.left.isSatisfiedBy(c) && this.right.isSatisfiedBy(c); }
  toString(): string { return `(${this.left} AND ${this.right})`; }
}

class OrSpec<T> extends Specification<T> {
  constructor(readonly left: Specification<T>, readonly right: Specification<T>) { super(); }
  isSatisfiedBy(c: T): boolean { return this.left.isSatisfiedBy(c) || this.right.isSatisfiedBy(c); }
  toString(): string { return `(${this.left} OR ${this.right})`; }
}

class NotSpec<T> extends Specification<T> {
  constructor(readonly inner: Specification<T>) { super(); }
  isSatisfiedBy(c: T): boolean { return !this.inner.isSatisfiedBy(c); }
  toString(): string { return `NOT ${this.inner}`; }
}

class InCategory extends Specification<Product> {
  constructor(readonly category: string) { super(); }
  isSatisfiedBy(p: Product): boolean { return p.category === this.category; }
  toString(): string { return `category = ${this.category}`; }
}

class PriceAtMost extends Specification<Product> {
  constructor(readonly cents: number) { super(); }
  isSatisfiedBy(p: Product): boolean { return p.priceCents <= this.cents; }
  toString(): string { return `price <= ${this.cents}`; }
}

class PriceAtLeast extends Specification<Product> {
  constructor(readonly cents: number) { super(); }
  isSatisfiedBy(p: Product): boolean { return p.priceCents >= this.cents; }
  toString(): string { return `price >= ${this.cents}`; }
}

class InStock extends Specification<Product> {
  isSatisfiedBy(p: Product): boolean { return p.stock > 0; }
  toString(): string { return "in stock"; }
}

class RatedAtLeast extends Specification<Product> {
  constructor(readonly stars: number) { super(); }
  isSatisfiedBy(p: Product): boolean { return p.rating >= this.stars; }
  toString(): string { return `rating >= ${this.stars}`; }
}

const CatalogRules = {
  freeShipping: (): Specification<Product> =>
    new InStock().and(new PriceAtLeast(5000)).and(new InCategory("furniture").not()),
  budgetPicks: (category: string): Specification<Product> =>
    new InCategory(category).and(new PriceAtMost(2000)).and(new RatedAtLeast(4)),
};

interface ProductRepository {
  findMatching(spec: Specification<Product>): Product[];
}

class InMemoryProductRepository implements ProductRepository {
  constructor(private readonly products: readonly Product[]) {}
  findMatching(spec: Specification<Product>): Product[] {
    return this.products.filter((p) => spec.isSatisfiedBy(p));
  }
}

const repo: ProductRepository = new InMemoryProductRepository([
  { sku: "LAMP-1", category: "lighting", priceCents: 5000, stock: 3, rating: 4.2 },
  { sku: "SOFA-9", category: "furniture", priceCents: 89900, stock: 1, rating: 4.8 },
  { sku: "BOOK-7", category: "books", priceCents: 1500, stock: 12, rating: 4.6 },
  { sku: "BOOK-8", category: "books", priceCents: 1800, stock: 0, rating: 4.9 },
  { sku: "BOOK-9", category: "books", priceCents: 1200, stock: 5, rating: 3.1 },
]);
const skus = (ps: Product[]) => ps.map((p) => p.sku).join(",");

assert(skus(repo.findMatching(CatalogRules.freeShipping())) === "LAMP-1");
assert(skus(repo.findMatching(CatalogRules.budgetPicks("books"))) === "BOOK-7,BOOK-8");
assert(skus(repo.findMatching(CatalogRules.budgetPicks("books").and(new InStock()))) === "BOOK-7");
assert(CatalogRules.freeShipping().isSatisfiedBy(
  { sku: "LAMP-1", category: "lighting", priceCents: 5000, stock: 3, rating: 4.2 }));

console.log(CatalogRules.freeShipping().toString());

Points worth calling out:

  • The rule now has a name from the business. freeShipping() is what product managers call it. When the threshold changes to $60, there's one line to edit, and checkout and search change together.
  • The repository shrank to one method. findMatching(spec) replaces the growing family of findXByYAndZ methods. New combinations are composed by the caller.
  • Leaves are values. Records and frozen dataclasses give value equality and readable toString output for free, which helps in logs ("filtered by (in stock AND price >= 5000)") and in tests.
  • The combinators live on the interface. In Java they're default methods, in TypeScript they're on the abstract base class, and in Python they're operator overloads (&, |, ~). Python's and, or and not keywords can't be overloaded, which is why libraries such as Django's Q objects and SQLAlchemy use the bitwise operators instead.

Functions as specifications

If all you need is in-memory filtering and validation, a plain predicate function already is a specification. Java's java.util.function.Predicate<T> even ships with the combinators:

import java.util.List;
import java.util.function.Predicate;

record Item(String name, long priceCents, int stock) {}

class PredicateDemo {
    static Predicate<Item> inStock() { return i -> i.stock() > 0; }
    static Predicate<Item> priceAtMost(long cents) { return i -> i.priceCents() <= cents; }

    public static void main(String[] args) {
        Predicate<Item> cheapAndAvailable = inStock().and(priceAtMost(1000));
        Predicate<Item> soldOutOrPricey = cheapAndAvailable.negate();

        List<Item> items = List.of(new Item("pen", 200, 10), new Item("bag", 4000, 2), new Item("cap", 900, 0));
        assert items.stream().filter(cheapAndAvailable).map(Item::name).toList().equals(List.of("pen"));
        assert items.stream().filter(soldOutOrPricey).count() == 2;
        System.out.println("Predicate is a ready-made specification");
    }
}

In TypeScript and Python, a function (p: Product) => boolean plus three tiny helpers (and, or, not) does the same job. So when do you need classes?

NeedFunctions are enoughYou need specification objects
Filter a list in memoryYes
Validate one objectYes
Explain which part failedYes: the tree can be inspected
Log or display the ruleYes: a lambda prints as an opaque address
Compare two rules for equality, cache by ruleYes: value objects compare by content
Translate into SQL, a search query or an API filterYes: you can't look inside a lambda
Store the rule and load it laterYes: a tree serialises, a closure doesn't

Start with functions. Switch to objects the moment a rule has to be inspected, not just run.

Specifications and repositories

The Repository pattern gives the domain a collection-like interface to storage. Specification gives that interface a query language made of domain concepts. Together, repository.findMatching(spec) lets a service ask for "free-shipping products" without knowing whether they come from a list, a SQL table or a search index.

The catch is obvious once you have real data: the in-memory implementation above loads every product and filters in application code. With a million rows, that's unusable. A specification that's going to drive a query must be translatable into the storage's own filter language.

There are two places to put that translation:

  1. On the specification itself (toSql() on every leaf). It's simple, but it puts SQL inside domain objects, and every new store (a search index, a cache) adds another method to every leaf.
  2. In an infrastructure-side translator that walks the specification tree and emits the query. The domain stays clean, and each store gets its own translator. This is the Visitor idea, and with pattern matching it's one function.

The example below takes the second route. It's complete and runnable: it builds an in-memory SQLite database with Python's standard library, translates specifications into a parameterised WHERE clause, and checks that the database and the in-memory evaluation return the same rows for several rules. That last check is the most valuable test you can write for a translatable specification, because the two paths can easily drift apart.

import sqlite3
from dataclasses import dataclass


@dataclass(frozen=True)
class Product:
    sku: str
    category: str
    price_cents: int
    stock: int


class Spec:
    def __and__(self, other): return And(self, other)
    def __or__(self, other): return Or(self, other)
    def __invert__(self): return Not(self)


@dataclass(frozen=True)
class And(Spec):
    left: Spec
    right: Spec

@dataclass(frozen=True)
class Or(Spec):
    left: Spec
    right: Spec

@dataclass(frozen=True)
class Not(Spec):
    inner: Spec

@dataclass(frozen=True)
class InCategory(Spec):
    category: str

@dataclass(frozen=True)
class PriceAtMost(Spec):
    cents: int

@dataclass(frozen=True)
class InStock(Spec):
    pass


def satisfied(spec: Spec, p: Product) -> bool:
    """Domain-side evaluation."""
    match spec:
        case And(l, r): return satisfied(l, p) and satisfied(r, p)
        case Or(l, r): return satisfied(l, p) or satisfied(r, p)
        case Not(s): return not satisfied(s, p)
        case InCategory(c): return p.category == c
        case PriceAtMost(c): return p.price_cents <= c
        case InStock(): return p.stock > 0
    raise TypeError(f"no evaluation for {spec!r}")


def to_sql(spec: Spec) -> tuple[str, list]:
    """Infrastructure-side translation. Column names are fixed here, never taken from input."""
    match spec:
        case And(l, r) | Or(l, r):
            (ls, lp), (rs, rp) = to_sql(l), to_sql(r)
            op = "AND" if isinstance(spec, And) else "OR"
            return f"({ls} {op} {rs})", lp + rp
        case Not(s):
            sql, params = to_sql(s)
            return f"(NOT {sql})", params
        case InCategory(c): return "category = ?", [c]
        case PriceAtMost(c): return "price_cents <= ?", [c]
        case InStock(): return "stock > 0", []
    raise TypeError(f"no SQL translation for {spec!r}")


class SqliteProductRepository:
    def __init__(self, conn: sqlite3.Connection) -> None:
        self._conn = conn

    def find_matching(self, spec: Spec) -> list[Product]:
        where, params = to_sql(spec)
        rows = self._conn.execute(
            f"SELECT sku, category, price_cents, stock FROM product WHERE {where} ORDER BY sku", params)
        return [Product(*row) for row in rows]


products = [
    Product("BOOK-7", "books", 1500, 12), Product("BOOK-8", "books", 1800, 0),
    Product("LAMP-1", "lighting", 5000, 3), Product("SOFA-9", "furniture", 89900, 1),
]
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE product (sku TEXT PRIMARY KEY, category TEXT, price_cents INTEGER, stock INTEGER)")
conn.executemany("INSERT INTO product VALUES (?, ?, ?, ?)",
                 [(p.sku, p.category, p.price_cents, p.stock) for p in products])
repo = SqliteProductRepository(conn)

rules = [
    InStock() & PriceAtMost(2000),
    InCategory("books") | InCategory("furniture"),
    ~InCategory("furniture") & ~InStock(),
    InCategory("x' OR '1'='1"),                         # hostile input stays a bound parameter
]
for rule in rules:
    in_db = [p.sku for p in repo.find_matching(rule)]
    in_memory = sorted(p.sku for p in products if satisfied(rule, p))
    assert in_db == in_memory, (rule, in_db, in_memory)

assert to_sql(InStock() & PriceAtMost(2000)) == ("(stock > 0 AND price_cents <= ?)", [2000])
assert repo.find_matching(rules[3]) == []
print("SQL and in-memory agree on", len(rules), "rules")

A few design notes on that example:

  • Values are bound parameters, column names are constants. The translator never pastes a value into the SQL text, so the hostile category string in the test is just a string that matches nothing. Column names come from the translator's code, not from the specification's data.
  • Unknown specifications fail loudly. If someone adds a leaf the translator doesn't know, it raises instead of silently dropping the condition. Dropping a condition from a WHERE clause returns more rows than intended, which can leak data.
  • Semantics must match. SQL has NULL, collations and case-sensitivity rules that Python, Java and TypeScript don't share. category = 'Books' may or may not match 'books' depending on the database's collation. The parity test catches these differences early.

What real frameworks do

  • Spring Data JPA has a Specification<T> interface whose single method, toPredicate(root, query, criteriaBuilder), builds a JPA Criteria predicate. Repositories that extend JpaSpecificationExecutor<T> gain findAll(spec), and specifications combine with and, or and Specification.not(...). That's the "translation on the specification" approach: each spec knows how to express itself in the Criteria API.
  • Django Q objects combine with &, | and ~ and are passed to filter(), and the ORM translates the tree into SQL. It's the same shape as our Python example.
  • .NET developers often express specifications as LINQ expression trees (Expression<Func<T, bool>>), which Entity Framework translates into SQL. Expression trees are data, not compiled code, which is exactly the inspectability requirement from the table above.

Explaining why a rule failed

Validation often needs more than yes or no. "Not eligible for free shipping" is a frustrating message. "Not eligible: the order total is below $50.00" is a useful one. Because a specification is a tree, it can report which leaves failed:

  • Leaves return a reason when unsatisfied ("price is below 5000").
  • And collects the reasons of all failing children (or only the first, if you want short messages).
  • Or fails only if all children fail, and reports all their reasons.
  • Not is the awkward one: it fails when its child succeeds, so the leaf needs a positive description to negate ("category is furniture").

This is one of the strongest arguments for objects over plain functions. A lambda can tell you false. A tree can tell you why.

Pitfalls

  • Specification explosion. Creating a class for every conceivable condition (PriceBetween10And20) misses the point. Keep leaves parameterised and few, and create named rules by composition.
  • Leaking evaluation cost. findMatching with an untranslatable specification quietly loads the whole table. Make the in-memory repository explicit about being for tests, and make the production translator refuse anything it can't translate.
  • Mixing invariants with selection. "A product's price is never negative" is an invariant that belongs in the Product constructor. Specifications are for rules that may or may not hold, such as eligibility and selection criteria. Don't use a specification to check something that should be impossible.
  • Deep trees from long chains. a.and(b).and(c).and(d) builds a left-leaning tree, which is fine for dozens of conditions but not for thousands generated by a program. For big generated rules, use AllOf(list) and AnyOf(list) nodes that hold many children.
  • Generic repositories everywhere. findMatching(spec) is a great addition to a specific repository. It's not a reason to replace every intent-revealing method (findOverdueLoans()) with an anonymous specification at each call site. Named methods and named specifications can coexist.

Real-world uses

  • Spring Data JPA Specification<T> with JpaSpecificationExecutor.findAll(spec), described above.
  • Java's Predicate<T>, with and, or, negate and Predicate.not, used across the Streams API as an in-memory specification.
  • Django Q objects and SQLAlchemy's and_, or_ and not_ expressions: composable query criteria translated into SQL.
  • LINQ expression trees in .NET, translated by Entity Framework into SQL, and libraries such as Ardalis.Specification that package the pattern for EF Core.
  • Search filters in e-commerce and admin UIs. The "filters" sidebar on a product listing is usually a list of leaf specifications ANDed together, translated into a search-engine query.

When NOT to use it

  • The rule is used in exactly one place. A private method named isFreeShippingEligible is clearer than a specification class hierarchy. Extract the specification when the second caller appears.
  • There are no combinations. If queries are a fixed handful (findByEmail, findOverdue), named repository methods are more readable and easier to optimise. Specifications pay off when callers combine conditions freely.
  • Performance depends on hand-tuned queries. A generated WHERE clause can't use a carefully chosen index hint, a CTE or a denormalised table. For hot paths, write the query by hand behind a named repository method.
  • It's only in-memory and functions suffice. If you never need to inspect, display, store or translate the rule, Predicate<T> or a plain function gives you composition with no classes at all.
  • The "rules" are really configuration a user edits. Then you need a parser and a small language on top, which is the Interpreter pattern. Specifications can be the tree it produces.
  • Composite. AndSpec, OrSpec and NotSpec are composites of specifications. Specification is essentially Composite applied to boolean predicates, plus a domain vocabulary.
  • Interpreter. Both build and/or/not trees. Interpreter starts from text written in a grammar and needs a parser. Specification is built in code by developers. A user-facing rule editor typically parses text with Interpreter into a specification tree.
  • Strategy. A specification is a strategy whose algorithm returns a boolean. The difference is intent and composition: strategies are swapped, specifications are combined.
  • Visitor. Translating a specification into SQL, a search query or an explanation is a visitor over the specification tree, or a pattern-matching function in languages that have it.
  • Repository. The main consumer of specifications. findMatching(spec) replaces combinatorial finder methods.
  • Decorator. NotSpec wraps one specification and changes its answer, which looks like a decorator. The difference is that specifications compose into trees with several children, while decorators form a chain around one object.

The smell that suggests it

  • Finder methods with And in the name. findActiveByRegionAndPlanAndCreatedAfter is a query language encoded in method names.
  • The same boolean expression in several services. Especially with small differences (>= versus >) that nobody can explain.
  • Business rules hidden inside SQL strings or ORM calls. "Eligible customer" exists only as a WHERE clause in one query, so the API's validation can't reuse it.
  • Validation and filtering disagree. The UI lets you pick an option that the backend rejects, because each has its own copy of the rule.

Interview questions

  1. "What is a specification, in one sentence?" A business rule packaged as a named, composable predicate object with isSatisfiedBy, which can be combined with other rules using and, or and not.

  2. "How is Specification different from just passing a lambda?" For in-memory filtering, it isn't, and Java's Predicate is a fine specification. The difference appears when the rule must be inspected: explaining failures, logging, comparing, storing or translating into a query all need a tree of objects rather than an opaque function.

  3. "How do specifications relate to repositories?" They replace combinatorial finder methods with one findMatching(spec) method. The repository decides how to evaluate the specification: in memory for tests, or by translating it into a query for a real database.

  4. "How would you translate a specification into SQL safely?" Walk the tree in an infrastructure-side translator, emit fixed column names from code and bind every value as a parameter, never concatenate. Fail loudly on unknown specification types. Test that SQL and in-memory evaluation return the same results for the same data.

  5. "Where does the translation code belong: on the specification or outside it?" On the specification is simpler (Spring Data JPA does this), but it couples domain objects to one persistence technology. A separate translator keeps the domain clean and allows several stores. In an interview, state the trade-off and pick one deliberately.

  6. "What are the three uses of a specification?" Validation (does this object satisfy the rule?), selection (find all objects that satisfy it) and construction (build an object guaranteed to satisfy it, for example generating test data or a default configuration). The first two are by far the most common.

  7. "Can a specification express 'not'? Any pitfalls?" Yes, with a NotSpec wrapper. The pitfalls are explanations (a negated rule needs a positive description of the child to explain its failure) and SQL NULL: NOT (category = 'books') doesn't match rows whose category is NULL, while the in-memory version might.

  8. "When would you not use Specification?" When a rule is used in one place, when queries are a fixed small set that named methods cover, or when performance needs hand-written queries. It's a tool for rules that are shared and combined, not a mandatory layer.

Further reading