Specification Pattern
A Specification is one business rule packaged as an object with one method: isSatisfiedBy(candidate) returns true or false. Because the rule is an object and not an if, it has a type, a name and its own unit test, and and, or and not combine it with others into a bigger rule that is still one object of the same type. This is not a GoF pattern – it comes out of Domain-Driven Design, named by Eric Evans and written up by Evans and Martin Fowler – and the payoff is that a predicate becomes a thing you can name, reuse, compose, explain and sometimes translate into a query.
💡 Predicate = a side-effect-free function from one candidate to true or false. A Specification is a predicate with an identity: a type, a name, and parts you can inspect rather than only call.
Why this matters: every problem involving filters, eligibility, matching or search has a predicate at its centre, so this pattern turns up in machine-coding rounds constantly without being named, and the interviewer is watching how you package it. Two things get graded. First, whether you can justify a class at all when Predicate<T> already composes with and and or – there are exactly three good reasons and a strong candidate lists them. Second, what happens when the candidates live in a database table rather than a list, which is where this pattern stops being free.
Prerequisites
- Strategy Pattern – a Specification is shaped like a Strategy whose return type is boolean and whose job is to answer, never to act
- Composite Pattern –
and,orandnotare composites over the interface they implement, which is what lets a rule nest to any depth - Repository Pattern – where a specification usually gets passed, and the reason translating one into a query is the hard part
The Problem: findFiles has six parameters and a hardcoded AND
A file-search utility written the obvious way, in the shape of the find command – one parameter per criterion, and a body that checks each one that was supplied:
public List<Path> findFiles(String namePattern, Long minSize, Long maxSize,
Instant modifiedAfter, boolean includeHidden,
Set<String> extensions) throws IOException {
List<Path> results = new ArrayList<>();
for (Path path : walk(root)) {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
if (namePattern != null
&& !globMatcher(namePattern).matches(path.getFileName())) continue;
if (minSize != null && attrs.size() < minSize) continue;
if (maxSize != null && attrs.size() > maxSize) continue;
if (modifiedAfter != null && !attrs.lastModifiedTime().toInstant()
.isAfter(modifiedAfter)) continue;
if (!includeHidden && Files.isHidden(path)) continue;
if (extensions != null && !extensions.contains(extensionOf(path))) continue;
results.add(path);
}
return results;
}
// This tuple is what the team means by "stale log file". Nothing says so.
List<Path> stale = search.findFiles("*.log", 104857600L, null, null, false,
Set.of("log"));
On the day it is written this is the right amount of code. Three costs arrive later, and all three are things an interviewer pushes on.
- The signature grows one parameter per criterion, and every caller pays for all of them. Six parameters, five nullable, and the call above passes three nulls purely to say nothing about them. “Modified before a cutoff” needs a bound the signature never built, so it becomes a seventh parameter and a recompile of every call site – and a
SearchCriteriaobject only hides that, because the body still knows every criterion. - The combinator is hardcoded as AND, so a whole class of queries is inexpressible. Every
continueis an implicit AND and no parameter has a value meaning “or”, so “name matches*.logOR extension isgz” cannot be written through this signature at any length. Two searches and a union at the call site is the workaround, and it collapses once the OR sits inside an AND:(name matches OR extension is) AND larger than 100MBhas no two-search equivalent. - No individual rule has a name, so none can be tested or reused. “Stale log file” exists only as the tuple
("*.log", 104857600, null, null, false, {"log"}), copied between the cleanup job, the disk-pressure alert and the admin console, so moving the policy to 14 days means grepping three services for a magic number. And “larger than 100MB” has no unit test because no such rule exists – onlyattrs.size() < minSizeinside a loop that walks a real filesystem.
What you want is each criterion as a value you can hold: name it, test it, pass it around, and glue it to another one with AND or OR without touching the search code.
Class Diagram
classDiagram
class Specification {
<<interface>>
+isSatisfiedBy(T candidate) boolean
+and(other) Specification~T~
+or(other) Specification~T~
+not() Specification~T~
}
class AndSpecification {
-Specification~T~ left
-Specification~T~ right
}
Specification <|.. NameMatches
Specification <|.. LargerThan
Specification <|.. ModifiedBefore
Specification <|.. HasExtension
Specification <|.. AndSpecification
Specification <|.. OrSpecification
Specification <|.. NotSpecification
Specification <|.. StaleLogFile
AndSpecification o-- Specification
OrSpecification o-- Specification
NotSpecification o-- Specification
StaleLogFile o-- Specification
AndSpecification o-- Specification aggregates the interface AndSpecification itself implements – the Composite recursion, and the reason a rule nests arbitrarily while callers still see one Specification. StaleLogFile sits on the same implements line as the leaves even though it holds a composite: to its callers it is one named rule, and that it is three ANDs inside is nobody’s business.
Real-World Example: File Search with Specifications
public interface Specification<T> { // isSatisfiedBy is the whole contract
boolean isSatisfiedBy(T candidate);
// Defaults, so a new leaf is one class with one method and still composes.
default Specification<T> and(Specification<T> o) { return new AndSpecification<>(this, o); }
default Specification<T> or(Specification<T> o) { return new OrSpecification<>(this, o); }
default Specification<T> not() { return new NotSpecification<>(this); }
}
// Specs read this snapshot and never touch the disk, so their tests need no
// temp directory.
public record FileInfo(Path path, long sizeBytes, Instant lastModified,
boolean hidden, String extension) {}
public final class LargerThan implements Specification<FileInfo> {
private final long bytes;
public LargerThan(long bytes) { this.bytes = bytes; }
@Override public boolean isSatisfiedBy(FileInfo f) { return f.sizeBytes() > bytes; }
public long bytes() { return bytes; } // the query translator reads this
@Override public String toString() { return "size > " + bytes; }
}
// Same shape for the rest: NameMatches holds a glob plus the PathMatcher
// compiled from it once, ModifiedBefore an Instant cutoff (an instant, not a
// Duration, so the rule cannot drift), HasExtension a Set.copyOf allowlist.
public final class AndSpecification<T> implements Specification<T> {
private final Specification<T> left, right;
public AndSpecification(Specification<T> l, Specification<T> r) {
left = requireNonNull(l); right = requireNonNull(r);
}
@Override public boolean isSatisfiedBy(T candidate) {
// && short-circuits: an expensive leaf placed second is skipped once a
// cheap leaf first returns false, so order your ANDs.
return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
}
public Specification<T> left() { return left; } // a translator walks the
public Specification<T> right() { return right; } // tree through these two
}
// Or is this class with || in place of &&; Not holds one child and inverts it.
/** The payoff: "stale log file" is what the on-call team says out loud, so
* here it is a type, not a tuple copied between services. */
public final class StaleLogFile implements Specification<FileInfo> {
public static final long MB_100 = 100L * 1024 * 1024;
private final Specification<FileInfo> rule;
public StaleLogFile(Clock clock) { // Clock injected, so the rule is
this.rule = new NameMatches("*.log") // testable at any wall-clock time
.and(new LargerThan(MB_100))
.and(new ModifiedBefore(clock.instant().minus(Duration.ofDays(30))));
}
@Override public boolean isSatisfiedBy(FileInfo f) { return rule.isSatisfiedBy(f); }
@Override public String toString() { return "stale log file"; }
} // The cutoff is fixed at construction: build it per run, or it goes stale.
// In memory the line reads as the rule, which is the ergonomic win.
List<FileInfo> stale = entries.stream()
.filter(new StaleLogFile(Clock.systemUTC())::isSatisfiedBy).toList();
// And the OR the six-parameter signature could not express. Chaining has NO
// precedence -- a.or(b).and(c) is (a OR b) AND c -- so group by nesting.
Specification<FileInfo> archivable = new NameMatches("*.log")
.or(new HasExtension(Set.of("gz", "zip"))).and(new LargerThan(MB_100));
public interface FileRepository { // in-memory: one stream filter over this.
List<FileInfo> findAll(Specification<FileInfo> spec, Pageable page);
} // In SQL: the next section.
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from fnmatch import fnmatch
MB_100 = 100 * 1024 * 1024
class Specification(ABC):
@abstractmethod
def is_satisfied_by(self, candidate) -> bool: ...
# Dunders, so composition reads as the rule: name_matches & larger_than.
# Python binds & tighter than |, so (a & b) | c needs no parentheses,
# unlike the Java fluent form, which is strictly left-associative.
def __and__(self, other): return And(self, other)
def __or__(self, other): return Or(self, other)
def __invert__(self): return Not(self) # ~spec
@dataclass(frozen=True, slots=True) # frozen: a rule is a value
class NameMatches(Specification):
glob: str
def is_satisfied_by(self, f) -> bool: return fnmatch(f.name, self.glob)
def __str__(self) -> str: return f"name matches {self.glob}"
# LargerThan, ModifiedBefore and HasExtension are the same four lines over an
# int, a datetime and a frozenset -- one comparison each, field exposed.
@dataclass(frozen=True, slots=True)
class And(Specification): # Or is this class with `or`; Not
left: Specification # inverts a single child
right: Specification
def is_satisfied_by(self, f) -> bool:
return self.left.is_satisfied_by(f) and self.right.is_satisfied_by(f)
def stale_log_file(now: datetime) -> Specification: # the named composite
# No class needed for a named composite: the factory carries the name,
# and the tree it returns is still introspectable.
return (NameMatches("*.log") & LargerThan(MB_100)
& ModifiedBefore(now - timedelta(days=30)))
spec = stale_log_file(datetime.now(timezone.utc))
stale = [f for f in entries if spec.is_satisfied_by(f)]
# ---- The version to reach for first: plain functions and all() ----
# Nothing above beats this until you need a name to pass around, a tree to
# introspect for a query, or an answer to "which rule rejected this one".
RULES = (lambda f: fnmatch(f.name, "*.log"), lambda f: f.size_bytes > MB_100)
stale = [f for f in entries if all(rule(f) for rule in RULES)]
#include <algorithm>
#include <functional>
#include <memory>
template <typename T>
class Specification {
public:
virtual ~Specification() = default;
// const: evaluating must not mutate the rule, which is what makes one spec
// object safe to share between composites and across threads.
virtual bool isSatisfiedBy(const T& candidate) const = 0;
};
// shared_ptr, not unique_ptr: one leaf is routinely referenced by several
// composites, and the leaves are immutable, so sharing costs nothing.
template <typename T>
using SpecPtr = std::shared_ptr<const Specification<T>>;
// Each leaf is one comparison plus an accessor the translator can read:
// LargerThan a std::uintmax_t, NameMatches a glob string, ModifiedBefore a
// file_time_type cutoff, HasExtension a std::set<std::string>.
template <typename T>
class AndSpecification : public Specification<T> {
SpecPtr<T> left_, right_;
public:
AndSpecification(SpecPtr<T> l, SpecPtr<T> r)
: left_(std::move(l)), right_(std::move(r)) {}
bool isSatisfiedBy(const T& c) const override {
return left_->isSatisfiedBy(c) && right_->isSatisfiedBy(c);
}
};
// A free operator&& over SpecPtr gives the fluent read, and it is safe because
// it evaluates nothing -- it builds a node, so the lost short-circuit costs
// nothing. Evaluation happens in the algorithm, one candidate at a time.
auto staleLogFile = nameMatches("*.log") && largerThan(MB_100)
&& modifiedBefore(cutoff);
std::copy_if(entries.begin(), entries.end(), std::back_inserter(out),
[&](const FileInfo& f) { return staleLogFile->isSatisfiedBy(f); });
// ---- The lambda shortcut, when none of the three reasons hold ----
// std::function<bool(const T&)> is the type-erased predicate; composing two
// is a lambda capturing two lambdas -- no classes, nothing to introspect.
using Predicate = std::function<bool(const FileInfo&)>;
Predicate both(Predicate a, Predicate b) {
return [a, b](const FileInfo& f) { return a(f) && b(f); };
}
The hard part is turning a specification into a query
In memory, isSatisfiedBy is trivial – a boolean expression over fields already in hand – and the pattern looks free. Then the candidates move into a table of fifty million rows, where findAll(spec) has one obvious implementation: SELECT *, hydrate every row, filter in the application. That is a full table scan and the whole table over the network to return forty rows. Three ways out, each with a cost.
1. In-memory only. Correct by construction, zero translation code, loads everything. It is the right choice more often than it sounds – a directory listing, one tenant’s catalogue – but only as a decision with a stated bound: tens of thousands of rows, not tens of millions, and a reason it cannot grow past that.
2. A translating visitor. Walk the spec tree and emit a WHERE fragment with bound parameters, a JPA Predicate or a Mongo filter: AndSpecification becomes (left) AND (right), LargerThan becomes size_bytes > ?. This is a Visitor over the spec tree, and composites translate structurally, so the cost lands on the leaves – each needs one translation per backend, which makes a new spec N edits. The failure is quiet: an unrecognised leaf drops out of the WHERE clause, the query returns a superset, nothing throws. And some leaves resist translation outright, since NameMatches takes a glob while SQL LIKE has only % and _.
3. Hybrid push-down. Push the leaves the store can evaluate into the query and evaluate the residue in memory on the much smaller result: size_bytes > ? AND last_modified < ? goes to the database with an index behind it, and the glob runs over the few thousand rows that come back. This is the usual production answer, and two things about it are worth knowing cold.
Push-down composes cleanly under AND and badly under OR: dropping an untranslatable conjunct just fetches a superset the in-memory pass cleans up, while dropping a disjunct loses rows the OR would have admitted, so one untranslatable leaf inside an OR makes that whole OR unpushable.
Then the trap: LIMIT plus residual in-memory filtering gives wrong page sizes. Ask for 20, the database returns 20, the residual filter rejects 6, and the caller gets 14 rows plus a cursor that advanced past rows nobody saw. Pagination and residual filtering do not compose, and every fix is unpleasant: over-fetch and loop until the page fills, which is unbounded work that still cannot honestly report a last page; refuse to paginate a spec with a residue; or denormalise what the residue needs into a column the store can filter, with an index on it.
Which leaves the rule tying all three together. isSatisfiedBy is the single source of truth for correctness; any query translation is an optimisation that must agree with it. You test that agreement rather than the SQL: run the spec in memory over the loaded candidates, run the translated query, assert the two result sets match.
Explaining a rejection
Extend the interface with a method returning which leaf said no. This is what most often makes the classes worth their cost, because “why was this order rejected” is a support ticket, a UI message and an audit row, and a bare boolean answers none of them.
public sealed interface Verdict {
record Satisfied() implements Verdict {}
record Rejected(List<Specification<?>> failing, String reason) implements Verdict {}
}
// On Specification<T>: every leaf inherits this and names itself when it fails.
default Verdict check(T candidate) {
return isSatisfiedBy(candidate) ? new Verdict.Satisfied()
: new Verdict.Rejected(List.of(this), toString());
}
// AndSpecification propagates the child's rejection unchanged, so the leaf
// that failed survives every composite above it.
@Override public Verdict check(T candidate) {
Verdict l = left.check(candidate);
if (l instanceof Verdict.Rejected) return l; // short-circuits, as AND does
return right.check(candidate);
}
The composites are where this gets interesting, and their asymmetry is the lesson. And propagates one rejection, since one failing conjunct explains the result; Or fails only when every branch failed, so its Rejected carries the full list and the message is “none of these matched”; Not cannot name a leaf at all, because what rejected the candidate is its child succeeding, so it reports itself. Keep both methods: isSatisfiedBy is the cheap short-circuiting path over a million candidates, check the explaining path you call once, for the candidate a human is asking about.
Specification vs Strategy vs Interpreter vs Chain vs a plain lambda
All five are behaviour behind an interface, which is why they blur. What separates them is what comes out, and where the rule came from.
| Pattern | Intent | Tell |
|---|---|---|
| Specification | Package one business rule as a composable boolean object | Returns true or false and never acts – the caller decides what the answer means |
| Strategy | Swap one algorithm behind one interface | It does something: returns a fare, sorts a list, writes the file |
| Interpreter | Evaluate a grammar authored outside the codebase | There is a grammar and a parser, and the tree arrives from a database row |
| Chain of Responsibility | Find the handler that applies, then let it act | Picks a link and acts; its boolean is plumbing, not the output |
| A predicate or lambda | The same composition with no classes | Identical behaviour, no name: f -> f.sizeBytes() > MB_100 |
Specification and Interpreter deserve the most care, because they produce the same shape of tree. A Specification is composed in code from typed parts, so the compiler checks every field reference; an Interpreter’s tree is built at runtime from data someone else wrote, so every one of those guarantees must be rebuilt as runtime validation. Build a grammar only when non-engineers author the rules.
The lambda row matters most, because in a modern language the lambda is not a weaker version of this pattern – it is this pattern. Java’s Predicate<T> already ships and, or and negate, each returning a composed predicate with the same short-circuiting; Python has plain functions and all(); C++ has std::function. Predicate<FileInfo> stale = isLog.and(largerThan).and(olderThan); is the same tree of the same composites, written by the standard library instead of by you.
So start with the lambda, and write classes only for one of the three things a lambda cannot give you: a domain name the whole codebase imports and can find usages of, rather than a name in one scope; introspection, because a Predicate is opaque and you cannot ask it for its size threshold or walk it, while query translation and a rule UI both need the parts; or a failure explanation, because check needs an identity to report and a lambda has nothing but a synthetic toString. If none of the three applies, the class is ceremony, and a good interviewer will say so before you do.
When to Use vs When to Avoid
| Use Specification When | Avoid When |
|---|---|
| The rule has a name the business says out loud – “stale log file”, “eligible for free shipping” | The predicate is used once, inline, and nobody has a name for it – use a lambda |
| The same rule is needed in several places: a filter, a guard, a nightly job | A single field already answers it, like order.isPaid() |
| Rules combine, and the combinator is not always AND | The rules are authored outside the codebase – that is Interpreter |
| A rule must be translated into a query against a store | The work is deciding how to act, not whether – that is Strategy |
| Someone has to be told which rule rejected a candidate | You need every failure at once, not the first – write a validator |
The characteristic failure mode is specification sprawl: thirty one-line classes, each a predicate used exactly once, each with a constructor, one field, a toString and a test asserting that 2 is greater than 1. The package looks rigorous and is strictly worse than f -> f.sizeBytes() > MB_100, because a reader now opens a file to learn what SizeAboveThreshold compares against what. Its cousin is the hardcoded-leaf explosion, LargerThan100MB and LargerThan1GB as separate types instead of one LargerThan(bytes). So: a predicate earns a class when it has a domain name, when it is reused, or when it must be translated – everything else stays a lambda. This is the textbook shape of Over-Engineering, where each class is individually defensible and the total is a directory nobody can hold in their head.
Interview Questions
-
“Specification or just a lambda?” – Default to the lambda:
Predicate<T>withand,orandnegatealready is this pattern and costs nothing. A class earns its place for exactly three reasons – a domain name the codebase can refer to, introspection for query translation or a rule UI, or an explanation of which rule rejected a candidate. A lambda gives none of those and beats a class at everything else, so “it’s cleaner” is not an answer. -
“How do you translate a composite spec into SQL without a case explosion?” – Composites translate structurally and only once, since
Andis always(left) AND (right)whatever the leaves are, so the risk sits entirely in the leaves. Shrink the leaf count by parameterising – oneFieldCompare(field, operator, value)replaces a dozen one-field classes – and make the dispatch exhaustive so a missed case is a compile error. Letting each leaf emit its own fragment is pleasant for one backend and wrong for three, because then every leaf imports SQL. -
“How does pagination interact with residual in-memory filtering?” – It breaks, quietly:
LIMIT 20is applied before the residual predicate runs, so if the in-memory pass rejects six rows the caller gets fourteen and a cursor that moved past rows nobody saw. There is no clean fix, only choices – over-fetch and loop until the page fills, which is unbounded work and cannot honestly report “no next page”; forbid pagination on a spec with a residue; or denormalise the field the residue needs into an indexed column so the residue is empty. -
“How do you keep in-memory and database evaluation consistent?” – Declare
isSatisfiedBythe source of truth, treat translation as an optimisation, and test the agreement rather than asserting on SQL strings. A dual-evaluation test seeds candidates, runs the spec in memory over all of them, runs the translated query and asserts the two sets match; a property-based test generates random spec trees and candidates and asserts the same equality, which is how you catch null columns, collation differences and timestamp precision at the database boundary. -
“How is validation different from specification?” – A specification answers one boolean and short-circuits by design; a validator must collect all failures, so it must not short-circuit, and it needs field paths so a UI can mark the right input. Conflating them is why a validator built out of specs cannot report more than the first error:
Andstops at the first false, so the other four violations are never evaluated. Build them as two things, or as one interface whose boolean and collecting methods have documented and different semantics.
See It in Action
- File Search – this lesson’s example: leaf specs over directory entries composed into named rules
- Discount Engine – cart eligibility as composed specs, with the rejection explained to the shopper
- Inventory Management – reorder and low-stock rules as named specs, pushed into the item query
- Mini ORM – the translating visitor itself: a spec tree walked into a parameterised
WHEREclause