Polski

Article · Specification · Composite

Specification: business rules as objects you can combine

The Specification pattern from Domain-Driven Design: named rules with isSatisfiedBy, combining with and, or and not, one rule for validation and querying, translation to SQL via expression trees, the Criteria API and Q objects. Code in C#, TypeScript, Java, Go and Python.

By · · 12 min read

A wholesaler sells to companies on trade credit: payment 30 days after delivery. The rule "who may buy on deferred payment" sounds simple – a verified company, no overdue invoices, at least six orders in the last year – but it lives in four places: the checkout, the sales panel, the e-mail campaign query and the finance report. Every copy is slightly different. The Specification pattern turns such a rule into an object named in the language of the domain that answers one question: does this candidate satisfy it?

2003
"Domain-Driven Design" – Eric Evans describes Specification among the patterns that make implicit concepts explicit
3
uses according to Evans – validation, selection from a collection, building objects to order
3
combinators – and, or, not – and no new repository methods

The problem: a rule scattered across the code

This is what the trade credit rule looked like after two years of development:

trade-credit.before.ts
// checkout
function canBuyOnCredit(c: Customer): boolean {
  return c.verified && c.taxId != null && c.overdueInvoices === 0 && c.ordersLastYear >= 6;
}

// e-mail campaign – copied, but someone "simplified" it and the SQL drifted away from the code above
const audience = await db.query(
  "SELECT * FROM customers WHERE verified = true AND orders_last_year >= 5", // taxId? overdue invoices?
);

// sales panel – yet another variant, with an extra exception nobody remembers
const eligible = customers.filter((c) => (c.verified || c.vip) && c.overdueInvoices === 0);

Three copies, three different answers to the same business question. When finance raises the threshold to eight orders, someone will change one place out of three. On top of that the rule has no name – the code shows conditions, but not the concept of "a customer eligible for trade credit".

The solution: named rules and combinators

Every condition becomes a separate specification: VerifiedCompany, HasOverdueInvoices, RegularBuyer. The shared interface has isSatisfiedBy plus combinators that return new specifications. The credit policy is simply a composition: VerifiedCompany and not HasOverdueInvoices and RegularBuyer. The checkout asks about one customer, the campaign about all of them, but both use the same object.

Diagram: Leaf specifications and combinators share one interface – the client cannot tell a simple rule from a composite one
RoleResponsibilityIn the example
Specificationthe interface: isSatisfiedBy + combinatorsSpecification<T>
Leaf specificationone named business ruleVerifiedCompany, HasOverdueInvoices
Combinatorcombines specifications logically and is a specification itselfAnd, Or, Not
Clientuses specifications to validate, select or buildcheckout, repository, campaign

Implementation in five languages

The C# version builds the specification on an expression tree (Expression<Func<T, bool>>), so EF Core translates it to SQL. TypeScript and Go show a functional style with rule names, which makes it possible to tell a customer why they were refused. Java uses the ready-made Specification<T> from Spring Data JPA, and Python overloaded operators plus Django's Q/Exists objects.

Trade credit policy

TradeCreditSpecs.cs
// A specification wraps an expression tree, so EF Core can translate it to SQL.
public abstract class Specification<T>
{
    private Func<T, bool>? _compiled;

    public abstract Expression<Func<T, bool>> ToExpression();

    // In memory: compile once and reuse – compiling on every call is expensive.
    public bool IsSatisfiedBy(T candidate) => (_compiled ??= ToExpression().Compile())(candidate);

    public Specification<T> And(Specification<T> other) => new Binary(this, other, Expression.AndAlso);
    public Specification<T> Or(Specification<T> other) => new Binary(this, other, Expression.OrElse);
    public Specification<T> Not() => new Negation(this);

    private sealed class Binary(Specification<T> left, Specification<T> right,
        Func<Expression, Expression, BinaryExpression> combine) : Specification<T>
    {
        public override Expression<Func<T, bool>> ToExpression()
        {
            var l = left.ToExpression();
            var r = right.ToExpression();
            var rightBody = new SwapParameter(r.Parameters[0], l.Parameters[0]).Visit(r.Body); // x => l(x) && r(x)
            return Expression.Lambda<Func<T, bool>>(combine(l.Body, rightBody), l.Parameters);
        }
    }

    private sealed class Negation(Specification<T> inner) : Specification<T>
    {
        public override Expression<Func<T, bool>> ToExpression()
        {
            var e = inner.ToExpression();
            return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body), e.Parameters);
        }
    }

    private sealed class SwapParameter(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
    {
        protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : node;
    }
}

public sealed class VerifiedCompany : Specification<Customer>
{
    public override Expression<Func<Customer, bool>> ToExpression() => c => c.Verified && c.TaxId != null;
}

public sealed class HasOverdueInvoices : Specification<Customer>
{
    public override Expression<Func<Customer, bool>> ToExpression() =>
        c => c.Invoices.Any(i => !i.Paid && i.DueDate < DateTime.UtcNow);
}

// The same rule validates one customer and selects customers in the database:
//   var policy = new VerifiedCompany().And(new HasOverdueInvoices().Not());
//   if (!policy.IsSatisfiedBy(customer)) throw new TradeCreditRefused(customer.Id);
//   var audience = await db.Customers.Where(policy.ToExpression()).ToListAsync(ct);
trade-credit-specs.ts
// A specification is a named predicate; combinators build new specifications from existing ones.
export interface Spec<T> {
  readonly name: string;
  isSatisfiedBy(candidate: T): boolean;
}

export const spec = <T>(name: string, test: (c: T) => boolean): Spec<T> => ({ name, isSatisfiedBy: test });

export const and = <T>(...specs: Spec<T>[]): Spec<T> =>
  spec(specs.map((s) => s.name).join(" AND "), (c) => specs.every((s) => s.isSatisfiedBy(c)));

export const or = <T>(...specs: Spec<T>[]): Spec<T> =>
  spec(specs.map((s) => s.name).join(" OR "), (c) => specs.some((s) => s.isSatisfiedBy(c)));

export const not = <T>(s: Spec<T>): Spec<T> => spec(`NOT (${s.name})`, (c) => !s.isSatisfiedBy(c));

/** Names of the rules the candidate fails – ready for an error message or a UI hint. */
export const unmet = <T>(candidate: T, ...specs: Spec<T>[]): string[] =>
  specs.filter((s) => !s.isSatisfiedBy(candidate)).map((s) => s.name);

interface Customer {
  verified: boolean;
  taxId?: string;
  overdueInvoices: number;
  ordersLastYear: number;
}

export const verifiedCompany = spec<Customer>("verified company", (c) => c.verified && !!c.taxId);
export const noOverdueInvoices = spec<Customer>("no overdue invoices", (c) => c.overdueInvoices === 0);
export const regularBuyer = spec<Customer>("6+ orders last year", (c) => c.ordersLastYear >= 6);

const creditRules = [verifiedCompany, noOverdueInvoices, regularBuyer];
export const tradeCreditPolicy = and(...creditRules);

export function assertTradeCredit(customer: Customer): void {
  const missing = unmet(customer, ...creditRules); // validation with a reason
  if (missing.length) throw new Error(`Trade credit refused: ${missing.join(", ")}`);
}

export const creditAudience = (all: Customer[]) => all.filter((c) => tradeCreditPolicy.isSatisfiedBy(c)); // selection
CustomerSpecs.java
// Spring Data JPA: a Specification<T> builds a Criteria API predicate, the repository runs it as SQL.
public final class CustomerSpecs {
    private CustomerSpecs() {}

    public static Specification<Customer> verifiedCompany() {
        return (root, query, cb) -> cb.and(
            cb.isTrue(root.<Boolean>get("verified")),
            cb.isNotNull(root.get("taxId")));
    }

    public static Specification<Customer> hasOverdueInvoices(LocalDate today) {
        return (root, query, cb) -> {
            Subquery<Long> overdue = query.subquery(Long.class);
            Root<Invoice> invoice = overdue.from(Invoice.class);
            overdue.select(cb.literal(1L)).where(
                cb.equal(invoice.get("customer"), root),
                cb.isFalse(invoice.<Boolean>get("paid")),
                cb.lessThan(invoice.<LocalDate>get("dueDate"), today));
            return cb.exists(overdue);
        };
    }

    public static Specification<Customer> placedAtLeast(int orders) {
        return (root, query, cb) -> cb.greaterThanOrEqualTo(root.<Integer>get("ordersLastYear"), orders);
    }
}

public interface CustomerRepository extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {}

@Service
class TradeCreditService {
    private final CustomerRepository customers;
    private final Clock clock;

    TradeCreditService(CustomerRepository customers, Clock clock) {
        this.customers = customers;
        this.clock = clock;
    }

    List<Customer> creditAudience() {
        Specification<Customer> policy = CustomerSpecs.verifiedCompany()
            .and(Specification.not(CustomerSpecs.hasOverdueInvoices(LocalDate.now(clock))))
            .and(CustomerSpecs.placedAtLeast(6));
        return customers.findAll(policy); // one SQL query with EXISTS, nothing filtered in memory
    }
}
specs.go
package credit

import "strings"

// Spec is a named business rule; generics (Go 1.18+) make the combinators reusable for any type.
type Spec[T any] struct {
	Name string
	Test func(T) bool
}

func (s Spec[T]) IsSatisfiedBy(c T) bool { return s.Test(c) }

func And[T any](specs ...Spec[T]) Spec[T] {
	names := make([]string, len(specs))
	for i, s := range specs {
		names[i] = s.Name
	}
	return Spec[T]{Name: strings.Join(names, " AND "), Test: func(c T) bool {
		for _, s := range specs {
			if !s.Test(c) {
				return false // short-circuit like &&
			}
		}
		return true
	}}
}

func Not[T any](s Spec[T]) Spec[T] {
	return Spec[T]{Name: "NOT (" + s.Name + ")", Test: func(c T) bool { return !s.Test(c) }}
}

// Unmet returns the names of the rules the candidate fails – handy for error messages.
func Unmet[T any](c T, specs ...Spec[T]) []string {
	var failed []string
	for _, s := range specs {
		if !s.Test(c) {
			failed = append(failed, s.Name)
		}
	}
	return failed
}

type Customer struct {
	Verified        bool
	TaxID           string
	OverdueInvoices int
	OrdersLastYear  int
}

var (
	VerifiedCompany   = Spec[Customer]{"verified company", func(c Customer) bool { return c.Verified && c.TaxID != "" }}
	NoOverdueInvoices = Spec[Customer]{"no overdue invoices", func(c Customer) bool { return c.OverdueInvoices == 0 }}
	RegularBuyer      = Spec[Customer]{"6+ orders last year", func(c Customer) bool { return c.OrdersLastYear >= 6 }}
	TradeCreditPolicy = And(VerifiedCompany, NoOverdueInvoices, RegularBuyer)
)
specs.py
from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Generic, TypeVar

T = TypeVar("T")


@dataclass(frozen=True)
class Spec(Generic[T]):
    """A named business rule; &, | and ~ build new specifications."""

    name: str
    test: Callable[[T], bool]

    def is_satisfied_by(self, candidate: T) -> bool:
        return self.test(candidate)

    def __and__(self, other: Spec[T]) -> Spec[T]:
        return Spec(f"{self.name} AND {other.name}", lambda c: self.test(c) and other.test(c))

    def __or__(self, other: Spec[T]) -> Spec[T]:
        return Spec(f"{self.name} OR {other.name}", lambda c: self.test(c) or other.test(c))

    def __invert__(self) -> Spec[T]:
        return Spec(f"NOT ({self.name})", lambda c: not self.test(c))


@dataclass
class Customer:
    verified: bool
    tax_id: str | None
    overdue_invoices: int
    orders_last_year: int


verified_company = Spec[Customer]("verified company", lambda c: c.verified and c.tax_id is not None)
no_overdue_invoices = Spec[Customer]("no overdue invoices", lambda c: c.overdue_invoices == 0)
regular_buyer = Spec[Customer]("6+ orders last year", lambda c: c.orders_last_year >= 6)
trade_credit_policy = verified_company & no_overdue_invoices & regular_buyer

# Django ORM: Q and Exists are specifications the ORM translates to SQL.
#   overdue = Invoice.objects.filter(customer=OuterRef("pk"), paid=False, due_date__lt=today)
#   audience = Customer.objects.filter(Q(verified=True, tax_id__isnull=False, orders_last_year__gte=6), ~Exists(overdue))

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not
  • Related patterns
  • In practice
  • Check yourself
  • Practice challenge

Create a free account · Sign in