Skip to content

Mathematical Foundations ​

Beneath the practical power of specifications lies elegant mathematics. Understanding these foundations transforms you from a specification user to a specification master.

The Beautiful Truth ​

Specifications are applied mathematics. Every specification is:

  • A predicate function from mathematical logic
  • A set membership test from set theory
  • A boolean expression from boolean algebra

This isn't abstract theoryβ€”it's the foundation that guarantees your business logic is correct.

Boolean Algebra: The Core ​

The Fundamental Operations ​

Specifications implement the three basic boolean operations:

php
// AND: Conjunction (∧)
$spec1->and($spec2)  // Both must be true

// OR: Disjunction (∨)  
$spec1->or($spec2)   // At least one must be true

// NOT: Negation (Β¬)
$spec->not()         // Inverts the result

Truth Tables ​

Every specification operation has a precise truth table:

AND Operation ​

spec1spec2spec1 ∧ spec2
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR Operation ​

spec1spec2spec1 ∨ spec2
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT Operation ​

spec¬spec
truefalse
falsetrue

Boolean Laws in Specifications ​

These mathematical laws guarantee predictable behavior:

Commutative Laws ​

php
// AND is commutative
$a->and($b) ≑ $b->and($a)

// OR is commutative
$a->or($b) ≑ $b->or($a)

Associative Laws ​

php
// AND is associative
($a->and($b))->and($c) ≑ $a->and($b->and($c))

// OR is associative
($a->or($b))->or($c) ≑ $a->or($b->or($c))

Distributive Laws ​

php
// AND distributes over OR
$a->and($b->or($c)) ≑ ($a->and($b))->or($a->and($c))

// OR distributes over AND
$a->or($b->and($c)) ≑ ($a->or($b))->and($a->or($c))

De Morgan's Laws ​

php
// NOT of AND
$a->and($b)->not() ≑ $a->not()->or($b->not())

// NOT of OR
$a->or($b)->not() ≑ $a->not()->and($b->not())

Proof: De Morgan's Law in Practice ​

php
class DeMorganProof extends TestCase
{
    public function test_de_morgan_and_law()
    {
        $activeSpec = new WhereSpecification('status', 'active');
        $verifiedSpec = new WhereSpecification('verified', true);
        
        // Left side: NOT (A AND B)
        $leftSide = $activeSpec->and($verifiedSpec)->not();
        
        // Right side: (NOT A) OR (NOT B)
        $rightSide = $activeSpec->not()->or($verifiedSpec->not());
        
        // Test with all possible inputs
        $testCases = [
            ['status' => 'active', 'verified' => true],
            ['status' => 'active', 'verified' => false],
            ['status' => 'inactive', 'verified' => true],
            ['status' => 'inactive', 'verified' => false],
        ];
        
        foreach ($testCases as $case) {
            $candidate = (object) $case;
            $this->assertEquals(
                $leftSide->isSatisfiedBy($candidate),
                $rightSide->isSatisfiedBy($candidate),
                "De Morgan's law failed for: " . json_encode($case)
            );
        }
    }
}

Set Theory: The Structure ​

Specifications as Sets ​

Every specification defines a set:

php
$activeUsers = new WhereSpecification('status', 'active');
// Defines the set: {u ∈ Users | u.status = 'active'}

$premiumUsers = new WhereSpecification('subscription', 'premium');
// Defines the set: {u ∈ Users | u.subscription = 'premium'}

Set Operations Through Specifications ​

Intersection (AND) ​

php
$activePremium = $activeUsers->and($premiumUsers);
// Set intersection: ActiveUsers ∩ PremiumUsers

Union (OR) ​

php
$activeOrPremium = $activeUsers->or($premiumUsers);
// Set union: ActiveUsers βˆͺ PremiumUsers

Complement (NOT) ​

php
$inactiveUsers = $activeUsers->not();
// Set complement: Users \ ActiveUsers

Set Difference ​

php
$activeNonPremium = $activeUsers->and($premiumUsers->not());
// Set difference: ActiveUsers \ PremiumUsers

Venn Diagrams in Code ​

php
class SetOperationsSpecification
{
    public function visualizeVennDiagram()
    {
        $setA = new WhereSpecification('category', 'electronics');
        $setB = new WhereSpecification('price', '>', 100);
        
        return [
            'only_A' => $setA->and($setB->not()),           // A \ B
            'only_B' => $setB->and($setA->not()),           // B \ A
            'both_A_and_B' => $setA->and($setB),            // A ∩ B
            'either_A_or_B' => $setA->or($setB),            // A βˆͺ B
            'neither_A_nor_B' => $setA->not()->and($setB->not()), // (A βˆͺ B)'
        ];
    }
}

Predicate Logic: The Language ​

First-Order Logic ​

Specifications are predicates in first-order logic:

php
// Predicate: IsActive(x)
class IsActiveSpecification extends AbstractSpecification
{
    public function isSatisfiedBy(mixed $x): bool
    {
        return $x->status === 'active';
    }
}

// Universal quantification: βˆ€x ∈ Users, IsActive(x)
$allUsersActive = User::all()->every(
    fn($user) => $isActiveSpec->isSatisfiedBy($user)
);

// Existential quantification: βˆƒx ∈ Users, IsActive(x)
$someUserActive = User::all()->contains(
    fn($user) => $isActiveSpec->isSatisfiedBy($user)
);

Logical Implications ​

php
class ImplicationSpecification extends AbstractSpecification
{
    public function __construct(
        private SpecificationInterface $antecedent,
        private SpecificationInterface $consequent
    ) {}
    
    public function isSatisfiedBy(mixed $candidate): bool
    {
        // P β†’ Q ≑ Β¬P ∨ Q
        return !$this->antecedent->isSatisfiedBy($candidate) ||
               $this->consequent->isSatisfiedBy($candidate);
    }
}

// If user is premium, then they must be verified
$premiumImpliesVerified = new ImplicationSpecification(
    new WhereSpecification('subscription', 'premium'),
    new WhereNullSpecification('email_verified_at', false)
);

Category Theory: The Abstraction ​

Specifications as Morphisms ​

In category theory terms:

  • Objects are your domain entities
  • Morphisms are specifications
  • Composition is specification chaining
php
// Morphism composition
class MorphismComposition
{
    // f: A β†’ B (specification that maps A to boolean)
    private SpecificationInterface $f;
    
    // g: B β†’ C (specification that maps B to boolean)
    private SpecificationInterface $g;
    
    // g ∘ f: A β†’ C (composition)
    public function compose(): SpecificationInterface
    {
        return $this->f->and($this->g);
    }
}

Functors and Natural Transformations ​

php
// Functor: Maps specifications to queries
class SpecificationToQueryFunctor
{
    public function map(SpecificationInterface $spec): Builder
    {
        return $spec->toQuery(new Builder());
    }
}

// Natural transformation: Between functors
class CacheableTransformation
{
    public function transform(SpecificationInterface $spec): CacheableSpecification
    {
        return new CacheableSpecification($spec);
    }
}

Lattice Theory: The Hierarchy ​

Specifications Form a Boolean Lattice ​

php
class SpecificationLattice
{
    // Top element (always true)
    public function top(): SpecificationInterface
    {
        return new AlwaysTrueSpecification();
    }
    
    // Bottom element (always false)
    public function bottom(): SpecificationInterface
    {
        return new AlwaysFalseSpecification();
    }
    
    // Join (least upper bound) - OR
    public function join(SpecificationInterface $a, SpecificationInterface $b): SpecificationInterface
    {
        return $a->or($b);
    }
    
    // Meet (greatest lower bound) - AND
    public function meet(SpecificationInterface $a, SpecificationInterface $b): SpecificationInterface
    {
        return $a->and($b);
    }
    
    // Complement
    public function complement(SpecificationInterface $spec): SpecificationInterface
    {
        return $spec->not();
    }
}

Partial Order Relations ​

php
class SpecificationOrder
{
    // a ≀ b if a implies b
    public function lessThanOrEqual(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): bool {
        // For all x, if a(x) then b(x)
        return $this->implies($a, $b);
    }
    
    private function implies(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): bool {
        // Test with sample data
        foreach ($this->generateTestCases() as $case) {
            if ($a->isSatisfiedBy($case) && !$b->isSatisfiedBy($case)) {
                return false;
            }
        }
        return true;
    }
}

Computational Complexity ​

Time Complexity Analysis ​

php
class ComplexityAnalysis
{
    public function analyzeSpecification(SpecificationInterface $spec): array
    {
        return [
            'evaluation_complexity' => $this->evaluationComplexity($spec),
            'query_complexity' => $this->queryComplexity($spec),
            'composition_depth' => $this->compositionDepth($spec),
            'space_complexity' => $this->spaceComplexity($spec),
        ];
    }
    
    private function evaluationComplexity(SpecificationInterface $spec): string
    {
        if ($spec instanceof WhereSpecification) {
            return 'O(1)'; // Constant time comparison
        }
        
        if ($spec instanceof AndSpecification || $spec instanceof OrSpecification) {
            return 'O(n)'; // Linear in number of sub-specifications
        }
        
        if ($spec instanceof WhereHasSpecification) {
            return 'O(m)'; // Linear in related records
        }
        
        return 'O(n*m)'; // Worst case
    }
}

Formal Verification ​

Proving Specification Correctness ​

php
class SpecificationProof
{
    /**
     * Prove that a specification satisfies its invariants
     */
    public function proveInvariants(SpecificationInterface $spec): bool
    {
        // Invariant 1: Double negation elimination
        $doubleNegation = $spec->not()->not();
        assert($this->equivalent($spec, $doubleNegation));
        
        // Invariant 2: Idempotence of AND
        $idempotentAnd = $spec->and($spec);
        assert($this->equivalent($spec, $idempotentAnd));
        
        // Invariant 3: Idempotence of OR
        $idempotentOr = $spec->or($spec);
        assert($this->equivalent($spec, $idempotentOr));
        
        // Invariant 4: Identity elements
        $withTrue = $spec->and(new AlwaysTrueSpecification());
        assert($this->equivalent($spec, $withTrue));
        
        $withFalse = $spec->or(new AlwaysFalseSpecification());
        assert($this->equivalent($spec, $withFalse));
        
        return true;
    }
    
    private function equivalent(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): bool {
        // Test equivalence with exhaustive cases
        foreach ($this->generateAllPossibleInputs() as $input) {
            if ($a->isSatisfiedBy($input) !== $b->isSatisfiedBy($input)) {
                return false;
            }
        }
        return true;
    }
}

Algebraic Properties ​

The Specification Monoid ​

php
class SpecificationMonoid
{
    // Identity element for AND
    public function andIdentity(): SpecificationInterface
    {
        return new AlwaysTrueSpecification();
    }
    
    // Identity element for OR
    public function orIdentity(): SpecificationInterface
    {
        return new AlwaysFalseSpecification();
    }
    
    // Associative binary operation
    public function combine(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): SpecificationInterface {
        return $a->and($b); // or $a->or($b) for OR-monoid
    }
    
    // Fold operation
    public function fold(array $specifications): SpecificationInterface
    {
        return array_reduce(
            $specifications,
            fn($carry, $spec) => $carry ? $carry->and($spec) : $spec,
            $this->andIdentity()
        );
    }
}

The Specification Ring ​

php
class SpecificationRing
{
    // Addition operation (OR)
    public function add(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): SpecificationInterface {
        return $a->or($b);
    }
    
    // Multiplication operation (AND)
    public function multiply(
        SpecificationInterface $a,
        SpecificationInterface $b
    ): SpecificationInterface {
        return $a->and($b);
    }
    
    // Additive identity (always false)
    public function zero(): SpecificationInterface
    {
        return new AlwaysFalseSpecification();
    }
    
    // Multiplicative identity (always true)
    public function one(): SpecificationInterface
    {
        return new AlwaysTrueSpecification();
    }
    
    // Additive inverse (not possible in boolean algebra)
    // Multiplicative inverse (not defined for all elements)
}

Practical Mathematical Applications ​

Optimization Through Algebra ​

php
class AlgebraicOptimizer
{
    public function optimize(SpecificationInterface $spec): SpecificationInterface
    {
        // Apply algebraic simplifications
        
        // Remove double negations
        if ($spec instanceof NotSpecification) {
            $inner = $spec->getSpecification();
            if ($inner instanceof NotSpecification) {
                return $this->optimize($inner->getSpecification());
            }
        }
        
        // Simplify tautologies
        if ($spec instanceof AndSpecification) {
            if ($spec->getLeft() instanceof AlwaysTrueSpecification) {
                return $this->optimize($spec->getRight());
            }
            if ($spec->getRight() instanceof AlwaysTrueSpecification) {
                return $this->optimize($spec->getLeft());
            }
        }
        
        // Apply absorption law: A ∨ (A ∧ B) = A
        // Apply other algebraic laws...
        
        return $spec;
    }
}

Statistical Analysis ​

php
class SpecificationStatistics
{
    public function analyzeSelectivity(SpecificationInterface $spec, array $dataset): array
    {
        $satisfied = array_filter(
            $dataset,
            fn($item) => $spec->isSatisfiedBy($item)
        );
        
        $total = count($dataset);
        $selected = count($satisfied);
        
        return [
            'selectivity' => $selected / $total,
            'cardinality' => $selected,
            'entropy' => $this->calculateEntropy($selected, $total),
            'information_gain' => $this->calculateInformationGain($spec, $dataset),
        ];
    }
    
    private function calculateEntropy(int $positive, int $total): float
    {
        if ($positive === 0 || $positive === $total) {
            return 0;
        }
        
        $p = $positive / $total;
        $n = 1 - $p;
        
        return -($p * log($p, 2) + $n * log($n, 2));
    }
}

The Mathematical Beauty ​

Specifications aren't just practicalβ€”they're mathematically elegant:

  1. Closure: Operations always produce valid specifications
  2. Completeness: Can express any boolean logic
  3. Soundness: Mathematical laws always hold
  4. Decidability: Always terminate with true/false

Your Mathematical Toolkit ​

With these foundations, you can:

  • Prove your business logic is correct
  • Optimize specifications algebraically
  • Predict performance mathematically
  • Compose with mathematical confidence

The Power of Math

Understanding the mathematics behind specifications transforms you from someone who uses the pattern to someone who masters it.

Ready for Domain-Driven Design? ​

Now that you understand the mathematical foundations, see how specifications bridge the gap between business language and code.

Explore Domain-Driven Design β†’

References ​

  1. Boole, George (1854). An Investigation of the Laws of Thought. Cambridge: Macmillan and Co.

  2. Halmos, Paul R. (1960). Naive Set Theory. Princeton, NJ: D. Van Nostrand Company.

  3. Mendelson, Elliott (2015). Mathematical Logic. 4th ed. Chapman and Hall/CRC. ISBN 978-1-4822-3778-8.

  4. Rosen, Kenneth H. (2018). Discrete Mathematics and Its Applications. 8th ed. McGraw-Hill Education. ISBN 978-1-259-67651-2.

  5. Mac Lane, Saunders (1998). Categories for the Working Mathematician. 2nd ed. Springer-Verlag. ISBN 0-387-98403-8.

  6. Knuth, Donald E. (1997). The Art of Computer Programming, Volume 1: Fundamental Algorithms. 3rd ed. Addison-Wesley. ISBN 0-201-89683-4.

  7. Pierce, Benjamin C. (1991). Basic Category Theory for Computer Scientists. MIT Press. ISBN 0-262-66071-7.

  8. Birkhoff, Garrett & Bartee, Thomas C. (1970). Modern Applied Algebra. McGraw-Hill.

  9. Davey, B.A. & Priestley, H.A. (2002). Introduction to Lattices and Order. 2nd ed. Cambridge University Press. ISBN 0-521-78451-4.

Released under the MIT License.