Skip to content
jshacks.dev
Patterns

The Specification Pattern in JavaScript Explained

The Specification pattern turns business rules into small objects you can combine with and, or and not. See it in JavaScript with filters, validation and tests.

8 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, Node.js, Vite, npm and TypeScript logos.

The Specification pattern packages a business rule as a small object that answers one question about a candidate: does this satisfy me? Specifications can be combined with and, or and not, so a complex rule is built from simple named ones. This post builds the pattern in JavaScript on Node.js 24, from a single rule to composed filters and readable failure reasons, and compares it with the lighter approach of composing plain predicate functions.

The problem: rules buried in conditions

An online shop decides which customers get a free-shipping offer. The rule starts simple and grows.

tangled.mjsJavaScript
function eligibleForFreeShipping(customer, cart) {
  return (
    (customer.tier === "gold" || cart.total >= 100) &&
    !cart.items.some((item) => item.oversized) &&
    customer.country === "VN"
  );
}

const customer = { tier: "silver", country: "VN" };
const cart = { total: 120, items: [{ oversized: false }] };
console.log(eligibleForFreeShipping(customer, cart));
Text
true

It works, but the rule has no names. A reader must decode the boolean to learn that "gold or big spender" is one idea and "nothing oversized" is another. The same sub-rules also appear in other places: a report listing gold customers, an email targeting big spenders. Each copy can drift.

One specification per idea

Give each rule a name and a single method.

specs.mjsJavaScript
class Specification {
  isSatisfiedBy() {
    throw new Error("not implemented");
  }
  and(other) {
    return new And(this, other);
  }
  or(other) {
    return new Or(this, other);
  }
  not() {
    return new Not(this);
  }
}

class And extends Specification {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  isSatisfiedBy(x) {
    return this.a.isSatisfiedBy(x) && this.b.isSatisfiedBy(x);
  }
}

class Or extends Specification {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  isSatisfiedBy(x) {
    return this.a.isSatisfiedBy(x) || this.b.isSatisfiedBy(x);
  }
}

class Not extends Specification {
  constructor(a) {
    super();
    this.a = a;
  }
  isSatisfiedBy(x) {
    return !this.a.isSatisfiedBy(x);
  }
}

class GoldTier extends Specification {
  isSatisfiedBy({ customer }) {
    return customer.tier === "gold";
  }
}

class BigSpender extends Specification {
  constructor(min) {
    super();
    this.min = min;
  }
  isSatisfiedBy({ cart }) {
    return cart.total >= this.min;
  }
}

class HasOversizedItem extends Specification {
  isSatisfiedBy({ cart }) {
    return cart.items.some((item) => item.oversized);
  }
}

class InCountry extends Specification {
  constructor(code) {
    super();
    this.code = code;
  }
  isSatisfiedBy({ customer }) {
    return customer.country === this.code;
  }
}

const freeShipping = new GoldTier()
  .or(new BigSpender(100))
  .and(new HasOversizedItem().not())
  .and(new InCountry("VN"));

const order = {
  customer: { tier: "silver", country: "VN" },
  cart: { total: 120, items: [{ oversized: false }] },
};
console.log(freeShipping.isSatisfiedBy(order));
console.log(
  freeShipping.isSatisfiedBy({ ...order, customer: { tier: "silver", country: "US" } }),
);
Text
true
false

The final rule reads like the requirement: gold or big spender, and nothing oversized, and in Vietnam. Each piece is reusable. The report of gold customers uses new GoldTier() directly.

Filtering a list

A specification works as the argument to filter, which is its most common use.

filter.mjsJavaScript
const orders = [
  { id: 1, customer: { tier: "gold", country: "VN" }, cart: { total: 20, items: [] } },
  { id: 2, customer: { tier: "silver", country: "VN" }, cart: { total: 150, items: [] } },
  { id: 3, customer: { tier: "gold", country: "VN" }, cart: { total: 500, items: [{ oversized: true }] } },
  { id: 4, customer: { tier: "gold", country: "US" }, cart: { total: 500, items: [] } },
];

const eligible = orders.filter((o) => freeShipping.isSatisfiedBy(o));
console.log(eligible.map((o) => o.id));
Text
[ 1, 2 ]

Order 3 fails the oversized rule and order 4 fails the country rule. The business rule exists once, and any code that needs the list of eligible orders applies the same object.

Saying why a rule failed

A boolean cannot tell a support agent why a customer was refused. A specification can return a reason with the result.

reasons.mjsJavaScript
const rule = (name, test) => ({
  name,
  check: (x) => (test(x) ? { ok: true } : { ok: false, failed: [name] }),
});

function allOf(...rules) {
  return {
    check(x) {
      const failed = rules.flatMap((r) => r.check(x).failed ?? []);
      return failed.length ? { ok: false, failed } : { ok: true };
    },
  };
}

const eligibility = allOf(
  rule("no oversized items", ({ cart }) => !cart.items.some((i) => i.oversized)),
  rule("ships to Vietnam", ({ customer }) => customer.country === "VN"),
  rule("order of 100 or more", ({ cart }) => cart.total >= 100),
);

console.log(eligibility.check(orders[0]));
console.log(eligibility.check(orders[2]));
Text
{ ok: false, failed: [ 'order of 100 or more' ] }
{ ok: true }

Collecting every failed rule, not just the first, lets the message say everything that needs fixing in one go. Each rule's name is a sentence a person can read, so it doubles as the explanation.

Specifications as plain functions

JavaScript does not need classes for this. Predicates are functions, and combinators are higher-order functions.

functional.mjsJavaScript
const and = (...ps) => (x) => ps.every((p) => p(x));
const or = (...ps) => (x) => ps.some((p) => p(x));
const not = (p) => (x) => !p(x);

const goldTier = ({ customer }) => customer.tier === "gold";
const bigSpender = (min) => ({ cart }) => cart.total >= min;
const hasOversized = ({ cart }) => cart.items.some((i) => i.oversized);
const inCountry = (code) => ({ customer }) => customer.country === code;

const freeShipping = and(
  or(goldTier, bigSpender(100)),
  not(hasOversized),
  inCountry("VN"),
);

console.log(orders.filter(freeShipping).map((o) => o.id));
Text
[ 1, 2 ]

The result matches the class version with a fraction of the code. Choose classes when specifications need more than a yes or no, such as a description, a reason or a translation into a database query. Choose functions when a boolean is enough.

Translating a specification into a query

The strongest reason for the class form is that a specification object can be inspected, which a function cannot. A rule built from objects can be translated into a SQL WHERE clause or a search filter, so the same business rule filters rows in the database and in memory.

to-sql.mjsJavaScript
class Gte {
  constructor(field, value) {
    this.field = field;
    this.value = value;
  }
  toSql() {
    return { sql: `${this.field} >= ?`, params: [this.value] };
  }
}
class Eq {
  constructor(field, value) {
    this.field = field;
    this.value = value;
  }
  toSql() {
    return { sql: `${this.field} = ?`, params: [this.value] };
  }
}
class AllOf {
  constructor(...parts) {
    this.parts = parts;
  }
  toSql() {
    const compiled = this.parts.map((p) => p.toSql());
    return {
      sql: compiled.map((c) => `(${c.sql})`).join(" AND "),
      params: compiled.flatMap((c) => c.params),
    };
  }
}

const spec = new AllOf(new Gte("total", 100), new Eq("country", "VN"));
console.log(spec.toSql());
Text
{ sql: '(total >= ?) AND (country = ?)', params: [ 100, 'VN' ] }

Field names come from code, not user input, and values travel as parameters, which keeps the generated query safe from injection. A real implementation would whitelist field names.

Testing specifications

Each small specification gets its own tiny test, and the composed rule gets one test per branch.

specs.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("BigSpender is inclusive at the threshold", () => {
  const spec = new BigSpender(100);
  assert.equal(spec.isSatisfiedBy({ cart: { total: 100 } }), true);
  assert.equal(spec.isSatisfiedBy({ cart: { total: 99.99 } }), false);
});
Text
✔ BigSpender is inclusive at the threshold (0.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

Boundary tests like this one are cheap to write because each rule is a separate object.

When not to use it

For one rule used in one place, an if is the clearest code. The pattern pays when rules are reused, combined in different ways, shown to users or turned into queries. If your rules change by editing a single function and nobody else needs a piece, skip the classes.

Specifications and domain language

The strongest effect of the pattern is on vocabulary. When a product manager says "free shipping applies to gold customers or big spenders, unless the cart has an oversized item", each phrase in that sentence becomes one specification, and the code can be read back to the person who asked for it. That is worth more than the mechanics of and and or. It means a rule change request maps to a small, local edit, and a disagreement about what a rule means can be settled by reading a few lines.

To keep this property, name specifications for the business idea and not for the implementation. BigSpender says why the rule exists, while CartTotalAtLeast100 says only what it checks. Keep thresholds as constructor parameters so one class serves several rules, and keep the classes free of I/O. A specification that queries a database inside isSatisfiedBy cannot be composed cheaply or tested without a database, so fetch the data first and pass it in.

Performance and ordering

A composed specification evaluates in the order you wrote it, and and and or short-circuit. That means the cheapest and most selective rule should come first. If one rule needs a network call and another compares two fields, put the field comparison first so the call only happens for candidates that pass it. For large lists, filter with the cheap rules, then apply the expensive one to what remains.

Be careful with specifications that depend on the current time, such as "subscription is active". Reading the clock inside the rule makes the same candidate satisfy it at one moment and not at the next, which complicates tests and caching. Pass the reference time in with the candidate, or give the specification a clock in its constructor, so tests can fix it.

Where specifications live in a codebase

Keep them next to the domain concept they describe, in a folder such as orders/specs, and export the composed rules the rest of the application uses by name, for example freeShipping. Other code should depend on freeShipping, not rebuild it from parts, so a change to the rule happens in one file. Small building blocks that several rules share can be exported too, but resist a large central library of specifications: a rule belongs to the domain that owns it, and a shared dumping ground slowly loses that ownership.

Adopting it in an existing codebase

You do not need to rewrite anything to start. Find a condition that has been copied into two or three places, give it a name, and extract it as a specification or a named predicate. Replace the copies one at a time, running the existing tests after each. The first extraction usually reveals that the copies were not quite identical, with one using > where another used >=, and deciding which is right is the real value of the exercise. Once two or three rules are extracted, composing them into the larger decision happens naturally, and the original tangled function shrinks to a single line that names the composed rule.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.