Programming Search⌘K

Patterncore

Specification

Also called specification pattern, Specification pattern, composite specification.

A specification is an object that tells if a candidate object matches some criteria. Specifications combine with and, or and not, and the same object can select, validate and describe.

Family
behavioral-design
Intent
Separate the statement of how to match a candidate from the candidate object that it is matched against, in an object with the method isSatisfiedBy.

Intent

Specification separates the statement of how to match a candidate from the candidate object that it is matched against. As well as its use in selection, it is also valuable for validation and for building to order.1

Problem

Evans and Fowler give three problems:1

  • Selection. You need to select a subset of objects based on some criteria, and to refresh the selection at various times. A trader monitors a portfolio of all contracts that involve the yen.
  • Validation. You need to check that only suitable objects are used for a certain purpose. A container for meat must be refrigerated and clean enough to store food.
  • Construction to order. You need to describe what an object might do, without the details of how it does it, so that a candidate can be built to fulfill the requirement. A shipping company builds a route from the constraints of a request.

If each of these places has its own copy of the test, the copies can drift apart. Here the selection of containers checks two conditions, but the validation checks only one:

This code runs but gives a wrong answer on purpose.

class Container:
    def __init__(self, name, refrigerated, clean):
        self.name = name
        self.refrigerated = refrigerated
        self.clean = clean


containers = [Container("c1", True, True), Container("c2", True, False)]

# selection: which containers can hold meat?
print("can hold meat:", [c.name for c in containers if c.refrigerated and c.clean])


# validation: may this container hold meat?
def assign_meat(container):
    if container.refrigerated:  # the clean test is missing here
        print(f"meat assigned to {container.name}")


assign_meat(containers[1])
Output
can hold meat: ['c1']
meat assigned to c2

Solution

Create a specification that can tell if a candidate object matches some criteria. The specification has a method isSatisfiedBy(anObject) that returns true if all criteria are met by anObject.1 Selection, validation and construction then use the same object.

A composite specification is a particular form of interpreter. Leaf elements are the different kinds of tests, and composite nodes are the and, or and not operators.1

               Specification
               isSatisfiedBy(candidate): bool
               and(other), or(other), not()
                     ^
        _____________|______________________
       |             |          |           |
   Refrigerated    Clean    AndSpec(a, b)  NotSpec(a)
   (leaf)          (leaf)   OrSpec(a, b)   (composite)
                            (composite)

A business rule can then be made from other rules. In the example of Wikipedia, an invoice goes to a collection agency if it is overdue, notices have been sent, and it is not already with the agency: overdue.And(noticeSent).And(inCollection.Not()).2

Example

The example files show one program in each language. Two leaf specifications test a container: Refrigerated and Clean. The program combines them with and, or and not, and selects from three containers. c1 is refrigerated and clean, c2 is refrigerated only, and c3 is clean only. The program prints:

meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
PythonGitHub
class Spec:
    def __and__(self, other):
        return AndSpec(self, other)

    def __or__(self, other):
        return OrSpec(self, other)

    def __invert__(self):
        return NotSpec(self)


class Refrigerated(Spec):
    def is_satisfied_by(self, c):
        return c.refrigerated


class Clean(Spec):
    def is_satisfied_by(self, c):
        return c.clean


class AndSpec(Spec):
    def __init__(self, a, b):
        self.a, self.b = a, b

    def is_satisfied_by(self, c):
        return self.a.is_satisfied_by(c) and self.b.is_satisfied_by(c)


class OrSpec(Spec):
    def __init__(self, a, b):
        self.a, self.b = a, b

    def is_satisfied_by(self, c):
        return self.a.is_satisfied_by(c) or self.b.is_satisfied_by(c)


class NotSpec(Spec):
    def __init__(self, a):
        self.a = a

    def is_satisfied_by(self, c):
        return not self.a.is_satisfied_by(c)


class Container:
    def __init__(self, name, refrigerated, clean):
        self.name, self.refrigerated, self.clean = name, refrigerated, clean


containers = [Container("c1", True, True), Container("c2", True, False), Container("c3", False, True)]


def select(spec):
    return ", ".join(c.name for c in containers if spec.is_satisfied_by(c))


print("meat:", select(Refrigerated() & Clean()))
print("not refrigerated:", select(~Refrigerated()))
print("refrigerated or clean:", select(Refrigerated() | Clean()))
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. The base class overloads &, | and ~, so specifications combine with operators.
#include <functional>
#include <iostream>
#include <string>
#include <vector>

struct Container {
    std::string name;
    bool refrigerated;
    bool clean;
};

class Spec {
public:
    explicit Spec(std::function<bool(const Container&)> test) : test_(std::move(test)) {}

    bool isSatisfiedBy(const Container& c) const { return test_(c); }

    Spec And(const Spec& other) const {
        Spec self = *this;
        return Spec([self, other](const Container& c) { return self.isSatisfiedBy(c) && other.isSatisfiedBy(c); });
    }
    Spec Or(const Spec& other) const {
        Spec self = *this;
        return Spec([self, other](const Container& c) { return self.isSatisfiedBy(c) || other.isSatisfiedBy(c); });
    }
    Spec Not() const {
        Spec self = *this;
        return Spec([self](const Container& c) { return !self.isSatisfiedBy(c); });
    }

private:
    std::function<bool(const Container&)> test_;
};

const std::vector<Container> containers = {{"c1", true, true}, {"c2", true, false}, {"c3", false, true}};

std::string select(const Spec& spec) {
    std::string out;
    for (const auto& c : containers) {
        if (!spec.isSatisfiedBy(c)) continue;
        if (!out.empty()) out += ", ";
        out += c.name;
    }
    return out;
}

int main() {
    Spec refrigerated([](const Container& c) { return c.refrigerated; });
    Spec clean([](const Container& c) { return c.clean; });

    std::cout << "meat: " << select(refrigerated.And(clean)) << "\n";
    std::cout << "not refrigerated: " << select(refrigerated.Not()) << "\n";
    std::cout << "refrigerated or clean: " << select(refrigerated.Or(clean)) << "\n";
}
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. Spec wraps a std::function, and each combined specification captures copies of its parts.
JavaGitHub
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

record Container(String name, boolean refrigerated, boolean clean) {}

public class Main {
    static final List<Container> CONTAINERS = List.of(
            new Container("c1", true, true),
            new Container("c2", true, false),
            new Container("c3", false, true));

    static String select(Predicate<Container> spec) {
        return CONTAINERS.stream().filter(spec).map(Container::name).collect(Collectors.joining(", "));
    }

    public static void main(String[] args) {
        Predicate<Container> refrigerated = Container::refrigerated;
        Predicate<Container> clean = Container::clean;

        System.out.println("meat: " + select(refrigerated.and(clean)));
        System.out.println("not refrigerated: " + select(refrigerated.negate()));
        System.out.println("refrigerated or clean: " + select(refrigerated.or(clean)));
    }
}
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: stdlib. java.util.function.Predicate has the default methods and, or and negate, so a predicate is a specification that combines.
using System;
using System.Collections.Generic;
using System.Linq;

record Container(string Name, bool Refrigerated, bool Clean);

class Spec<T>
{
    private readonly Func<T, bool> test;

    public Spec(Func<T, bool> test) => this.test = test;

    public bool IsSatisfiedBy(T candidate) => test(candidate);
    public Spec<T> And(Spec<T> other) => new Spec<T>(c => IsSatisfiedBy(c) && other.IsSatisfiedBy(c));
    public Spec<T> Or(Spec<T> other) => new Spec<T>(c => IsSatisfiedBy(c) || other.IsSatisfiedBy(c));
    public Spec<T> Not() => new Spec<T>(c => !IsSatisfiedBy(c));
}

class Program
{
    static readonly List<Container> Containers = new()
    {
        new Container("c1", true, true),
        new Container("c2", true, false),
        new Container("c3", false, true),
    };

    static string Select(Spec<Container> spec) =>
        string.Join(", ", Containers.Where(spec.IsSatisfiedBy).Select(c => c.Name));

    static void Main()
    {
        var refrigerated = new Spec<Container>(c => c.Refrigerated);
        var clean = new Spec<Container>(c => c.Clean);

        Console.WriteLine("meat: " + Select(refrigerated.And(clean)));
        Console.WriteLine("not refrigerated: " + Select(refrigerated.Not()));
        Console.WriteLine("refrigerated or clean: " + Select(refrigerated.Or(clean)));
    }
}
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. Spec<T> wraps a Func<T, bool>, and And, Or and Not return new specifications. The method group spec.IsSatisfiedBy is the filter for Where.
JavaScriptGitHub
class Spec {
  constructor(test) {
    this.test = test;
  }
  isSatisfiedBy(c) {
    return this.test(c);
  }
  and(other) {
    return new Spec((c) => this.isSatisfiedBy(c) && other.isSatisfiedBy(c));
  }
  or(other) {
    return new Spec((c) => this.isSatisfiedBy(c) || other.isSatisfiedBy(c));
  }
  not() {
    return new Spec((c) => !this.isSatisfiedBy(c));
  }
}

const refrigerated = new Spec((c) => c.refrigerated);
const clean = new Spec((c) => c.clean);

const containers = [
  { name: "c1", refrigerated: true, clean: true },
  { name: "c2", refrigerated: true, clean: false },
  { name: "c3", refrigerated: false, clean: true },
];

const select = (spec) =>
  containers.filter((c) => spec.isSatisfiedBy(c)).map((c) => c.name).join(", ");

console.log("meat:", select(refrigerated.and(clean)));
console.log("not refrigerated:", select(refrigerated.not()));
console.log("refrigerated or clean:", select(refrigerated.or(clean)));
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. Each specification wraps a test function, and and, or and not return new specifications.
TypeScriptGitHub
interface Container {
  name: string;
  refrigerated: boolean;
  clean: boolean;
}

class Spec<T> {
  private test: (candidate: T) => boolean;

  constructor(test: (candidate: T) => boolean) {
    this.test = test;
  }
  isSatisfiedBy(candidate: T): boolean {
    return this.test(candidate);
  }
  and(other: Spec<T>): Spec<T> {
    return new Spec((c) => this.isSatisfiedBy(c) && other.isSatisfiedBy(c));
  }
  or(other: Spec<T>): Spec<T> {
    return new Spec((c) => this.isSatisfiedBy(c) || other.isSatisfiedBy(c));
  }
  not(): Spec<T> {
    return new Spec((c) => !this.isSatisfiedBy(c));
  }
}

const refrigerated = new Spec<Container>((c) => c.refrigerated);
const clean = new Spec<Container>((c) => c.clean);

const containers: Container[] = [
  { name: "c1", refrigerated: true, clean: true },
  { name: "c2", refrigerated: true, clean: false },
  { name: "c3", refrigerated: false, clean: true },
];

function select(spec: Spec<Container>): string {
  return containers.filter((c) => spec.isSatisfiedBy(c)).map((c) => c.name).join(", ");
}

console.log("meat:", select(refrigerated.and(clean)));
console.log("not refrigerated:", select(refrigerated.not()));
console.log("refrigerated or clean:", select(refrigerated.or(clean)));
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. Spec<T> wraps a test function and is generic in the type of the candidate.
package main

import (
	"fmt"
	"strings"
)

type Container struct {
	Name         string
	Refrigerated bool
	Clean        bool
}

// Spec is a function type with methods that combine specifications.
type Spec func(Container) bool

func (s Spec) And(o Spec) Spec { return func(c Container) bool { return s(c) && o(c) } }
func (s Spec) Or(o Spec) Spec  { return func(c Container) bool { return s(c) || o(c) } }
func (s Spec) Not() Spec       { return func(c Container) bool { return !s(c) } }

var containers = []Container{{"c1", true, true}, {"c2", true, false}, {"c3", false, true}}

func selectNames(s Spec) string {
	var names []string
	for _, c := range containers {
		if s(c) {
			names = append(names, c.Name)
		}
	}
	return strings.Join(names, ", ")
}

func main() {
	refrigerated := Spec(func(c Container) bool { return c.Refrigerated })
	clean := Spec(func(c Container) bool { return c.Clean })

	fmt.Println("meat:", selectNames(refrigerated.And(clean)))
	fmt.Println("not refrigerated:", selectNames(refrigerated.Not()))
	fmt.Println("refrigerated or clean:", selectNames(refrigerated.Or(clean)))
}
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. Spec is a defined function type with the methods And, Or and Not, so a plain function literal becomes a specification by a conversion.
RustGitHub
struct Container {
    name: &'static str,
    refrigerated: bool,
    clean: bool,
}

// A composite specification as a tree: leaves are tests, other nodes are operators.
enum Spec {
    Refrigerated,
    Clean,
    And(Box<Spec>, Box<Spec>),
    Or(Box<Spec>, Box<Spec>),
    Not(Box<Spec>),
}

impl Spec {
    fn is_satisfied_by(&self, c: &Container) -> bool {
        match self {
            Spec::Refrigerated => c.refrigerated,
            Spec::Clean => c.clean,
            Spec::And(a, b) => a.is_satisfied_by(c) && b.is_satisfied_by(c),
            Spec::Or(a, b) => a.is_satisfied_by(c) || b.is_satisfied_by(c),
            Spec::Not(a) => !a.is_satisfied_by(c),
        }
    }
    fn and(self, other: Spec) -> Spec {
        Spec::And(Box::new(self), Box::new(other))
    }
    fn or(self, other: Spec) -> Spec {
        Spec::Or(Box::new(self), Box::new(other))
    }
    fn not(self) -> Spec {
        Spec::Not(Box::new(self))
    }
}

fn select(containers: &[Container], spec: &Spec) -> String {
    let names: Vec<&str> = containers.iter().filter(|c| spec.is_satisfied_by(c)).map(|c| c.name).collect();
    names.join(", ")
}

fn main() {
    let containers = [
        Container { name: "c1", refrigerated: true, clean: true },
        Container { name: "c2", refrigerated: true, clean: false },
        Container { name: "c3", refrigerated: false, clean: true },
    ];
    println!("meat: {}", select(&containers, &Spec::Refrigerated.and(Spec::Clean)));
    println!("not refrigerated: {}", select(&containers, &Spec::Refrigerated.not()));
    println!("refrigerated or clean: {}", select(&containers, &Spec::Refrigerated.or(Spec::Clean)));
}
Output
meat: c1
not refrigerated: c3
refrigerated or clean: c1, c2, c3
  • Verdict: idiom. An enum holds the leaf tests and the composite nodes, and one match interprets the tree. This is the Composite Specification form.

Consequences

The benefits:1

  • The design of requirements, fulfillment and validation is decoupled. Different parts of the system use the same constructs to express constraints, so similar code is not written many times.
  • The system definitions are more clear and declarative. A RouteSelector finds a Route that satisfies a RouteSpecification. This defines its responsibility, even if no isSatisfiedBy test is done.

The costs depend on the implementation:1

  • A hard-coded specification is easy and expressive, but inflexible. Each new specification needs a new class, and you usually cannot create new specifications at run time.
  • A composite specification is very flexible without many special classes, and it supports logical operations. But you must invest in a complex framework, and you are still limited by the leaf elements that are provided.
  • If you select from many candidates in a database, performance can become an issue. You must find a way to index the candidates.

This Python version overloads the operator &. The keyword and is a different operator. The expression x and y returns x if x is false, and otherwise returns y.3 An object is true by default, so and returns the second specification only:3

This code runs but gives a wrong answer on purpose.

class Spec:
    def __init__(self, name, test):
        self.name = name
        self.test = test

    def __and__(self, other):
        return Spec(f"{self.name} & {other.name}", lambda c: self.test(c) and other.test(c))


refrigerated = Spec("refrigerated", lambda c: c["refrigerated"])
clean = Spec("clean", lambda c: c["clean"])

print((refrigerated & clean).name)
print((refrigerated and clean).name)  # meant to be both tests
Output
refrigerated & clean
clean

When not to use it

The most common over-use is to build objects with flexible attributes from specifications. A specification has a clear responsibility: to identify an object that satisfies it, and to combine with other specifications. A route is not the same thing as a route specification. Evans and Fowler say that you should reconsider the pattern in these cases:1

  • You add to the protocol of the specification other than for initialization.
  • You do not use isSatisfiedBy.
  • The object represents an actual entity in the domain, not constraints on some other, possibly hypothetical, entity.
  • Hard Coded Specification codes the criteria in the isSatisfiedBy method. It treats the specification as a Strategy.1
  • Parameterized Specification has attributes for the values that commonly vary, so new specifications can be built at run time without programming.1
  • Composite Specification uses an Interpreter, with composite nodes for and, or and not.1
  • Subsumption compares two specifications. The operation isGeneralizationOf tells whether the receiver is in every way equal to or more general than the argument.1
  • Partially Satisfied Specification adds a method remainderUnsatisfiedBy. It returns a specification of only the requirements that the candidate does not meet, so it can explain to the user why the specification was not satisfied.1

This run block gives the unmet leaf tests of an and specification:

class Leaf:
    def __init__(self, name):
        self.name = name

    def is_satisfied_by(self, c):
        return c[self.name]

    def remainder_unsatisfied_by(self, c):
        return [] if self.is_satisfied_by(c) else [self.name]


class And:
    def __init__(self, *parts):
        self.parts = parts

    def is_satisfied_by(self, c):
        return all(p.is_satisfied_by(c) for p in self.parts)

    def remainder_unsatisfied_by(self, c):
        return [name for p in self.parts for name in p.remainder_unsatisfied_by(c)]


meat = And(Leaf("refrigerated"), Leaf("clean"))
c2 = {"refrigerated": True, "clean": False}
print("satisfied:", meat.is_satisfied_by(c2))
print("missing:", meat.remainder_unsatisfied_by(c2))
Output
satisfied: False
missing: ['clean']

The pattern is frequently used in the context of domain-driven design.2 Evans describes it in Domain-Driven Design.4

Known uses

  • In Spring Data JPA, the interface Specification<T> is a "Specification in the sense of Domain Driven Design". It has and, or and not, and its method toPredicate creates a WHERE clause for a query of the entity.5
  • Java's java.util.function.Predicate represents a boolean-valued function of one argument. Its default methods and and or return composed predicates, and negate returns the logical negation.6
  • Much of the experience of Evans and Fowler with the pattern was in a Smalltalk/Gemstone environment.1

References

  1. Eric Evans and Martin Fowler, Specifications, Introduction; pattern summary table; The Need for a Specification; Specification; Consequences of Specification; When Not to Use Specification; Hard Coded, Parameterized and Composite Specification; Partially Satisfied Specification; Final Thoughts
  2. Specification pattern, Wikipedia, Introduction; Example of use
  3. The Python Language Reference, 6.11 Boolean operations, 6.11 Boolean operations
  4. Eric Evans, Domain-Driven Design, Tackling Complexity in the Heart of Software, Addison-Wesley, 2003, Chapter 9, Specification
  5. Spring Data JPA 3.4.0 source, org/springframework/data/jpa/domain/Specification.java, interface Specification, lines 31 to 105
  6. Java SE 25 API, Interface Predicate, Interface description; Method Summary

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KM67J6/text.yaml