A tenant looking for a flat in Pune sets five filters: rent up to $2,500, at least 2 BHK (two bedrooms, plus a hall and kitchen), semi-furnished or better, not on the ground floor, and in Baner or Aundh. The app uses that rule three times: to filter the listings on the screen, to check every new listing for an alert, and to say which filters a missing flat fails.
Product filters, loan eligibility and a job board's saved searches work the same way: one rule made of small conditions, used in places that must agree.
The Specification pattern makes each small condition an object that answers "does this candidate pass?", and joins those objects with and, or and not. In this article we build the flat search twice. The first version passes every filter as a parameter. The second uses the Specification pattern. Then we look at what the pattern costs, when Java's own Predicate is enough, and how it differs from Interpreter, Composite and Strategy.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the parameter version, the rest from the finished design. Both programs run, and the outputs shown are what they print.
The search we are building
The search must:
- Filter on five conditions: rent at most some amount, at least some number of BHK, a minimum furnishing, the ground floor, and a list of localities. Rent is a whole number of dollars a month.
- Combine conditions with "and", "or" and "not", in any shape a tenant can describe.
- Search: return every listing the rule accepts, cheapest first.
- Alert: save a tenant's rule, and when a new listing arrives, say which tenants to tell.
- Explain: for one listing, list the parts of the rule it fails.
- Show the rule in words on the screen.
- Serve many tenants at once, on many threads.
This is the figure to draw first in an interview. It shows the real requirement: one rule, three callers. The design has to make sure the three callers can never disagree about what the rule means.
The first version: a parameter for every filter
The obvious design gives the search method one parameter per filter, with null meaning "any":
/** Each filter is a parameter, and null means "any". */ public List<Listing> search(List<Listing> listings, Integer maxRent, Integer minBhk, Furnishing minFurnishing, boolean skipGroundFloor, Set<String> localities) { List<Listing> found = new ArrayList<>(); for (Listing listing : listings) { if (maxRent != null && listing.rent() > maxRent) { continue; } if (minBhk != null && listing.bhk() < minBhk) { continue; } if (minFurnishing != null && !listing.furnishing().atLeast(minFurnishing)) { continue; } if (skipGroundFloor && listing.floor() == 0) { continue; } if (localities != null && !localities.contains(listing.locality())) { continue; } found.add(listing); } return found; }Each filter is an if that skips the listing. For one search screen with five fixed filters, this code is fine. The trouble starts when the alerts arrive. They need the same checks on one listing at a time, so the alert code gets its own copy:
private boolean matches(Listing listing, SavedAlert alert) { if (alert.maxRent() != null && listing.rent() >= alert.maxRent()) { return false; } if (alert.minBhk() != null && listing.bhk() < alert.minBhk()) { return false; } if (alert.minFurnishing() != null && !listing.furnishing().atLeast(alert.minFurnishing())) { return false; } if (alert.localities() != null && !alert.localities().contains(listing.locality())) { return false; } return true; }The demo runs Priya's search, then checks two new listings against her saved alert:
Priya's search finds: [L1, L2] L9: search shows it to Priya: true, alert tells [] L11: search shows it to Priya: false, alert tells [Priya]
The two copies have drifted. Line 18 says >= where the search says >, so the alert stays silent for L9 at exactly $2,500, a flat her search shows. The alert copy also has no ground-floor check, so it tells Priya about L11, a ground-floor flat her search hides. Nothing in the code ties the two copies together, and the compiler cannot see that they mean the same thing.
Each new filter changes every method and every caller. A pets-allowed filter is a seventh parameter on search, a new field on SavedAlert, a new if in both methods, and a new argument at every call. Two arguments of the same type passed in the wrong order still compile.
Some rules cannot be said at all. Rohan wants "a 2 BHK in Wakad or Hinjewadi for up to $2,000, or anything up to $1,200". A list of parameters can only say "and". The app would run two searches and merge them by hand, and then write that merge again for alerts.
Explaining a no is a third copy. To tell Priya why L3 is missing, the app needs the same five checks again, this time collecting the ones that fail.
All four problems have one cause. The rule is not a thing in this code. It is scattered across parameter lists and if statements, so each caller rebuilds it in its own way.
The idea
The pattern works like this:
- Each condition becomes an object with one method,
isSatisfiedBy(candidate), that answers yes or no. All of them implement one interface. - Conditions are joined by three more classes:
And,OrandNot. Each implements the same interface and holds the conditions it joins. - A rule is an object built from these pieces, in code, once. Callers pass it around like any other value.
- Every caller asks the same object. The search, the alert and the explanation each call the rule's methods, and none of them knows what the rule contains.
The interface is the specification. The small conditions, such as RentAtMost, are leaf specifications, and And, Or and Not are composite specifications, because they are built from other specifications.
Building it, step by step
Step 1: one interface for every rule
Every rule answers one question and can say what it is in words:
public interface Specification<T> { boolean isSatisfiedBy(T candidate); /** The rule in words, for the screen and for whyNot. */ String describe();isSatisfiedBy is the question. describe gives the rule in words, for the screen and for explanations. Without it, a rule could filter a list but could never tell a tenant what it was checking.
The interface is generic, so and, or and not work for rules about any type. Our rules are each a Specification<Listing>.
Step 2: small rules as records
Each condition is a record that holds its limit and implements the interface:
public record RentAtMost(int dollars) implements Specification<Listing> { public RentAtMost { if (dollars <= 0) { throw new IllegalArgumentException("the rent limit must be positive: " + dollars); } } @Override public boolean isSatisfiedBy(Listing listing) { return listing.rent() <= dollars; } @Override public String describe() { return String.format(Locale.ENGLISH, "rent at most $%,d", dollars); }}Line 18 is the whole rule: the listing's rent is at most the limit. The constructor refuses a limit of zero or less, because no flat could pass it and the mistake would show up only as an empty search. BhkAtLeast, FurnishedAtLeast and OnGroundFloor have the same shape.
InLocality holds a list, so it takes a copy:
public record InLocality(List<String> localities) implements Specification<Listing> { public InLocality { localities = List.copyOf(localities); if (localities.isEmpty()) { throw new IllegalArgumentException("name at least one locality"); } if (localities.stream().anyMatch(String::isBlank)) { throw new IllegalArgumentException("a locality must not be blank"); } if (new HashSet<>(localities).size() != localities.size()) { throw new IllegalArgumentException("a locality is named twice: " + localities); } } public InLocality(String... localities) { this(List.of(localities)); }Line 13 copies the caller's list into one that cannot change. If the app later adds "Wakad" to the list it built the rule from, the saved rule still means "Baner or Aundh". The constructor also refuses an empty list, a blank name and a name given twice.
One class per rule, or one class that names a field?
One FieldRule class with a field name, an operator and a value
new FieldRule("rent", "at most", 2_500) covers every filter with one class, so a new filter needs no new code. But the value is an Object, so the compiler cannot check it, and a misspelt field name is found only when the rule runs, if at all. That is the first problem the Interpreter pattern page meets, without the parser that solves it there.
One small record per ruleOur pick
Each rule has typed fields, checks its own input, and describes itself in its own words: "semi-furnished or better" reads better than "furnishing >= SEMI_FURNISHED". The cost is a new class for each new kind of filter. Each one is about twenty lines, and the existing classes do not change.
OnGroundFloor has no fields at all, so every new OnGroundFloor() behaves the same.
Step 3: and, or and not
The interface builds the three joining rules itself:
and and or are default methods, so every rule has them without writing anything. not is a static method, because not(new OnGroundFloor()) reads better than new OnGroundFloor().not(). Each one returns a new object and leaves the rules it was given unchanged.
Here is And:
record And<T>(Specification<T> left, Specification<T> right) implements Specification<T> { And { Objects.requireNonNull(left, "left"); Objects.requireNonNull(right, "right"); } @Override public boolean isSatisfiedBy(T candidate) { return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate); }Line 17 asks the left side first and asks the right side only if the left side passes. Java's && stops as soon as the answer is known, so a listing that fails on rent is never checked for locality. Or, on line 15 of its file, does the same with ||, and Not returns the opposite of the rule it holds.
And, Or and Not have no public modifier. Code outside the spec package cannot name them, and builds them only through and, or and not.
Where do and, or and not come from?
An abstract base class that every rule extends
A CompositeSpecification class holds and, or and not, and every rule extends it. This works, but it uses up each rule's one superclass. Records cannot extend a class at all, so every rule would have to be a hand-written class with its own equals and hashCode.
Default methods that return lambdas
and could return candidate -> isSatisfiedBy(candidate) && other.isSatisfiedBy(candidate), the way Java's Predicate does. Our interface has two abstract methods, isSatisfiedBy and describe, so a lambda cannot implement it. Even with only one, the two sides would be hidden inside the lambda, where no other method could reach them to describe the rule or explain a failure.
Default methods that build small recordsOur pick
and returns a new And record holding both sides. Any class or record can implement the interface, gets and and or without writing them, and can be passed to Specification.not. Because And keeps its two sides, it can describe itself and explain a failure, and two rules built the same way are equal. The cost is three small classes that callers never see.
Chained calls run from left to right, and each call wraps everything before it. Rohan's rule shows what that means:
Specification<Listing> rohan = new BhkAtLeast(2) .and(new InLocality("Wakad", "Hinjewadi")) .and(new RentAtMost(2_000)) .or(new RentAtMost(1_200));The or on line 52 wraps the whole chain before it. The rule describes itself as "(at least 2 BHK and in one of (Wakad, Hinjewadi) and rent at most $2,000) or rent at most $1,200", which is what Rohan asked for. To make an or apply to one part only, it has to go inside the call: a.and(b.or(c)).
A tenant who fills in the form may leave any filter empty, or all of them. The app makes one rule per filled-in field and joins them:
/** A rule every candidate passes: what a form with no filters chosen means. */ static <T> Specification<T> anything() { return new Anything<>(); } /** All the given rules joined with and, or anything() if there are none. */ static <T> Specification<T> allOf(List<Specification<T>> rules) { return rules.stream() .reduce(Specification::and) .orElseGet(Specification::anything); }allOf joins the rules with and on line 45. With no rules at all, line 46 returns anything(), a rule every listing passes. The demo's third tenant, Anil, leaves every field empty, and his search finds all eight listings.
Step 4: explaining a no
A tenant who wants to know why a flat is missing needs more than false. The interface has a second method for that:
/** The parts of this rule the candidate fails, in words. Empty when it passes. */ default List<String> whyNot(T candidate) { if (isSatisfiedBy(candidate)) { return List.of(); } return List.of(describe()); }By default, a rule that fails gives its own description as the one reason. That is right for every leaf: RentAtMost(2_000) fails with "rent at most $2,000". It is also what Or and Not use. A failing Or reports itself as one reason, because neither side passed and the tenant needs to change one of them. A failing Not reports "not on the ground floor".
Only And writes its own version:
@Override public List<String> whyNot(T candidate) { // Ask both sides, even after the left one fails, so the reader sees every reason at once. List<String> reasons = new ArrayList<>(left.whyNot(candidate)); reasons.addAll(right.whyNot(candidate)); return List.copyOf(reasons); }Lines 23 and 24 ask both sides and keep every reason. Unlike isSatisfiedBy, this method does not stop at the first failure, so a tenant sees everything wrong with a flat at once instead of fixing one filter and finding the next. The list it returns is a copy that the caller cannot change.
The two methods must agree: whyNot returns an empty list exactly when isSatisfiedBy returns true, for any rule that gives the same answer each time it is asked. The default gets this from its own if. And gets it because its list is empty only when both sides' lists are empty, and that happens only when both sides pass.
How does a rule say why it failed?
isSatisfiedBy returns a result with the reasons
One method answers both questions. But every search then builds a list of reasons for every listing it rejects, though nobody asked why. Every caller also has to unwrap the result just to get a yes or no.
A Visitor walks the tree and collects the reasons
The rule classes stay small, and each new question becomes a visitor class. But And, Or and Not would have to be public so a visitor could see them, and each would need an accept method. The Visitor pattern page shows when that trade pays off. For one extra question, it does not.
A second method, whyNot, with a defaultOur pick
Leaves get the method for free, and only And overrides it. A search calls only isSatisfiedBy and pays nothing for explanations. The cost is that two methods must agree. A new class that overrides whyNot must keep the rule above, so a check that compares both methods on many rules is worth writing.
Step 5: one rule, three jobs
FlatFinder holds the listings and the saved alerts. Its three jobs all take a Specification<Listing>:
/** Adds a listing and returns the tenants whose saved alert it matches, by name. */ public List<String> add(Listing listing) { Objects.requireNonNull(listing, "listing"); if (listings.putIfAbsent(listing.id(), listing) != null) { throw new IllegalArgumentException("a listing with id " + listing.id() + " already exists"); } List<String> tenants = new ArrayList<>(); for (Map.Entry<String, Specification<Listing>> alert : alerts.entrySet()) { try { if (alert.getValue().isSatisfiedBy(listing)) { tenants.add(alert.getKey()); } } catch (RuntimeException broken) { // One broken alert must not stop the listing or the other tenants' alerts. failedAlertChecks.incrementAndGet(); } } tenants.sort(null); return List.copyOf(tenants); } /** The listings the rule accepts, cheapest first. */ public List<Listing> search(Specification<Listing> rule) { Objects.requireNonNull(rule, "rule"); return listings.values().stream() .filter(rule::isSatisfiedBy) .sorted(CHEAPEST_FIRST) .toList(); } /** The parts of the rule one listing fails. Empty if it passes. */ public List<String> whyNot(String listingId, Specification<Listing> rule) { Objects.requireNonNull(listingId, "listingId"); Objects.requireNonNull(rule, "rule"); Listing listing = listings.get(listingId); if (listing == null) { throw new IllegalArgumentException("no listing with id " + listingId); } return rule.whyNot(listing); }Line 35 checks one new listing against each saved alert. Line 51 checks every listing against one rule. Line 64 asks one listing why it fails. All three call methods on the same rule object, so the alert and the search can no longer disagree about what the rule means. A new filter is a new rule class, and FlatFinder does not change.
A tenant's rule may include a check that can fail, such as one that asks another service for commute times. Lines 38 to 41 catch a RuntimeException from one alert, count it in failedAlertChecks(), and go on to the rest, so the other tenants are still told. A failed check is counted, not retried, and a real app would also log which alert failed and why. As on the Observer pattern page, an Error is let through. The listing is stored on line 29 before any alert runs, so a rule that looks at the stored listings sees it.
The checks run on the caller's thread, one after another. A rule that calls a slow service holds up add for every alert after it. Such a rule must answer quickly, or the app must match alerts off the add path, from a queue.
A rule never changes after it is built. Every rule class is a record, every field is final, and InLocality holds an unchangeable copy of its list. So one rule object can be checked by many threads at once with no lock. The listings and alerts live in ConcurrentHashMaps, and add uses putIfAbsent on line 29, so two threads adding the same id at once cannot both succeed.
demo/RaceCheck.java builds 2,000 listings and one shared copy of Priya's rule. Eight threads search with that rule 500 times each while a ninth thread adds 1,000 more listings, all too expensive to match. All nine start together:
8 threads ran 4,000 searches with one shared rule object. Each search should find 169 listings. Searches that did not: 0. Listings added during the searches: 1,000. Total now: 3,000.
Every search found the same 169 listings that one thread finds alone. A search running during an add may or may not see the new listing. Here none of the added listings can match, so the answer stays fixed.
The finished design
Here is one listing, L3, checked against Priya's rule in two ways:
The whole project is below. Click any class name in the code to open that class.
package spec; import java.util.List; /** * A rule that a candidate either meets or does not. Rules are built from * small ones with and, or and not, and the same rule object can filter a * list, check one new item and explain a no. */public interface Specification<T> { boolean isSatisfiedBy(T candidate); /** The rule in words, for the screen and for whyNot. */ String describe(); /** The parts of this rule the candidate fails, in words. Empty when it passes. */ default List<String> whyNot(T candidate) { if (isSatisfiedBy(candidate)) { return List.of(); } return List.of(describe()); } default Specification<T> and(Specification<T> other) { return new And<>(this, other); } default Specification<T> or(Specification<T> other) { return new Or<>(this, other); } static <T> Specification<T> not(Specification<T> rule) { return new Not<>(rule); } /** A rule every candidate passes: what a form with no filters chosen means. */ static <T> Specification<T> anything() { return new Anything<>(); } /** All the given rules joined with and, or anything() if there are none. */ static <T> Specification<T> allOf(List<Specification<T>> rules) { return rules.stream() .reduce(Specification::and) .orElseGet(Specification::anything); }}The demo in demo/Main.java adds eight listings, runs three tenants' rules, saves two of them as alerts, and adds four more listings:
Listings: L1 Baner $2,400 2 BHK semi-furnished floor 3 L2 Aundh $2,500 2 BHK fully furnished floor 5 L3 Baner $2,800 3 BHK fully furnished ground floor L4 Baner $2,200 2 BHK unfurnished floor 2 L5 Kothrud $2,100 2 BHK semi-furnished floor 4 L6 Aundh $1,900 1 BHK fully furnished floor 1 L7 Wakad $1,850 2 BHK semi-furnished ground floor L8 Hinjewadi $1,100 1 BHK unfurnished floor 6 Priya's rule: rent at most $2,500 and at least 2 BHK and semi-furnished or better and not on the ground floor and in one of (Baner, Aundh) search: L1 ($2,400), L2 ($2,500) why not L3: rent at most $2,500; not on the ground floor why not L4: semi-furnished or better why not L5: in one of (Baner, Aundh) why not L6: at least 2 BHK Rohan's rule: (at least 2 BHK and in one of (Wakad, Hinjewadi) and rent at most $2,000) or rent at most $1,200 search: L8 ($1,100), L7 ($1,850) why not L5: (at least 2 BHK and in one of (Wakad, Hinjewadi) and rent at most $2,000) or rent at most $1,200 Anil's rule: anything search: 8 listings Alerts saved for Priya and Rohan. New listings: L9 Aundh $2,500 3 BHK semi-furnished floor 2 -> tell Priya L10 Wakad $1,900 2 BHK unfurnished floor 1 -> tell Rohan L11 Baner $2,400 2 BHK semi-furnished ground floor -> tell nobody L12 Aundh $950 2 BHK fully furnished floor 4 -> tell Priya, Rohan
Priya's search finds L1 and L2, and L2 at exactly $2,500 passes. L3 fails two parts, and both appear in its reason. L4, L5 and L6 each fail one part. Rohan's search finds L8 for its low rent and L7 for the first part of his rule. L5 fails Rohan's whole rule, so his or is the one reason given. Anil's empty form finds all eight listings. When the new listings arrive, L9 at $2,500 now reaches Priya, the alert the first version missed. L11, on the ground floor, reaches nobody. L12 matches both rules, and both tenants are told.
What it costs
The pattern makes one kind of change cheap and another expensive.
A new rule is cheap. A "floor at most 4" filter, for a building without a lift, is one new record in the rule package. No existing class changes, and the new rule joins with the others through and and or at once.
A new question is expensive. Suppose the listings move to a database, and the app wants each rule turned into a query, so the database does the filtering. There are two ways. One is a new method, such as toQuery, in every rule class, including And, Or, Not and Anything. The other, which Spring Data JPA takes, is a separate interface whose only job is to build a query predicate. Either way it is new code for every rule, and a rule that calls another service may have no query at all.
There are smaller costs too. The rule is now spread across nine small classes instead of one method. And the left-to-right chaining in Step 3 can surprise a reader who expects and to bind tighter than or.
When a Predicate is enough
Java already has Predicate<T>, with default and, or and negate methods and a static Predicate.not. If a rule is used in one place, needs only a yes or no, and is never shown to a person, a lambda is shorter:
Predicate<Listing> affordable = listing -> listing.rent() <= 2_500;Predicate<Listing> bigEnough = listing -> listing.bhk() >= 2; List<Listing> found = listings.stream() .filter(affordable.and(bigEnough)) .toList();A Predicate built from lambdas cannot say what it checks. Its toString prints a generated class name, not the rule, and it cannot explain a failure. Two lambdas with the same code are also not equal, so a saved alert cannot be compared with a new one. When a rule must be described, explained, saved or compared, a specification earns its extra classes. Our rules still work wherever a Predicate is expected: rule::isSatisfiedBy is one, as line 51 of FlatFinder shows.
Specification, Interpreter or Strategy?
All three put a rule or a behaviour behind an interface, so they are easy to mix up.
| Specification | Interpreter | Strategy | |
|---|---|---|---|
| What it answers | Does this candidate pass? | What does this sentence of a small language mean for these facts? | How should this one job be done? |
| Where the rule comes from | Code builds it, often from a form | A parser reads it from text | The code that sets up the context picks one |
| Do the pieces combine | Yes, with and, or and not | Yes, by the grammar | No, one is used at a time |
| Example | Flat filters and alerts, on this page | Offer rules typed by an ops team, on the Interpreter pattern page | Shipping options, on the Strategy pattern page |
Composite is not a rival here but a part. And, Or and Not are a Composite, the way a folder is one on the Composite pattern page. Not wraps a single rule, which on its own would look like a decorator, but it is one more node in the same tree. The Interpreter pattern page describes this page's tree as its own tree without the parser. That page also shows one offer rule class chosen by setup code, which is a Strategy. A rule class becomes a Specification once rules are combined and shared by several callers.
A short way to say it: a specification is a yes-or-no rule built in code from small rules, and an interpreter is the same kind of tree read from text.
In an interview
The pattern sits inside low-level design questions with filters or eligibility: product search, flat or hotel search with saved alerts, loan or offer eligibility, and a job board's matching. Parking spot selection is another, where a spot must fit the vehicle and be free. The question does not need to name the pattern. It shows up as a rule that two parts of the system must apply the same way.
A good order for presenting it:
- Name the callers first. Say that the search, the alert and the explanation all apply one rule, and that the design must stop them drifting apart.
- Write the interface and one leaf in a few lines, then
and,orandnotas default methods. - Build one real rule with a chain, and say where the brackets fall.
- Add explanations if asked, as a second method that only
Andoverrides.
Common mistakes:
- Rules that can change after they are built. A rule that keeps the caller's list, or has a setter, can change under a saved alert. Make every rule immutable, and copy any collection it is given.
- Explanations that disagree with the answer. If
whyNotis written separately fromisSatisfiedBy, the two can drift exactly the way the first version's copies did. Build one from the other, or check that they agree. - Forgetting that chains read left to right.
a.and(b).or(c)is "(a and b) or c". If the intent is "a and (b or c)", writea.and(b.or(c)). - Assuming in-memory rules become database queries. A specification that checks objects in memory does not turn into SQL by itself. Turning it into a query needs a query method on every class, or a separate query interface.
Summary
- Use the Specification pattern when one rule made of small conditions must be applied in more than one place, and the places must agree.
- Each condition is a small immutable class with
isSatisfiedBy.And,OrandNotjoin them, and are themselves specifications. - Default methods on the interface build the joined rules, so any record can be a rule.
- A second method,
whyNot, explains a failure. OnlyAndoverrides it, and it must agree withisSatisfiedBy. - A new rule is cheap: one new class. A new question, such as turning rules into database queries, is new code for every class.
- If a rule is used once, needs only yes or no and is never shown to anyone, Java's
Predicateis enough.